0

I have a HTML form like this:

     <form id="myForm" name="myform" action="register/index.php" method="post" enctype="multipart/form-data" >

<input class="myfile" id="banner" name="banner" type="file" accept="image/png, image/gif, image/jpeg" >

<a href="#" onclick="getPreview();>Preview</a>

 <input type="submit"  value="submit" name="submit">

</form>

What I want to do is when a user clicks on the preview button his chosen file will display somewhere in <div id="myid"></div>

<script>

function getPreview(){

// what should write here to make this working
}

</script>

Anyone please help in this, how to do this using jQuery or JavaScript?

S.L. Barth
  • 7,954
  • 71
  • 47
  • 62
Fahad Ali
  • 79
  • 1
  • 14
  • http://stackoverflow.com/questions/4459379/preview-an-image-before-it-is-uploaded – Shree Dec 28 '16 at 06:16
  • i have edited your code in my answer as per your requirement, when you click on preview, then your image will be displayed – Ganesh Putta Dec 28 '16 at 06:20

1 Answers1

1

try this, may be this will help, else you can customize more as per your requirement

function readURL(input) {  
   $('.preview').show();
  $('#blah').hide();
  $('.preview').after('<img id="blah" src="#" alt="your image" style="display:none;"/>');
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function (e) {
      $('#blah')
      .attr('src', e.target.result)
      .width(150)
      .height(200);
    };
    reader.readAsDataURL(input.files[0]);
  }
}

function getPreview(){
  $('.preview').hide();
  $('#blah').show();
}
<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
   <div>
      <input type='file' onchange="readURL(this);" />
   </div>
  <div>
  <a href="#" class="preview" onclick="getPreview();">Preview</a><br/>   
    </div>
</body>
</html>
Ganesh Putta
  • 2,792
  • 13
  • 23