My jQuery
code isn't working. I want to display an image when user selects an input file. Please help.
I am using data-val
attribute to save the ID. Here is my code:
</script>
<script type="text/javascript">
function readURL(input, id) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(id).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
jQuery(document).on("change", "#imgInp", function(){
var id = jQuery(this).data("val");
readURL(this, id);
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<input type='file' data-val="#blash1" id="imgInp" />
<img id="blah1" src="#" alt="your image" />
<br>
<input type='file' data-val="#blash2" class="imgInp" />
<img id="blah2" src="" alt="your image" />
<br>
<input type='file' data-val="#blash3" class="imgInp" />
<img id="blah3" src="" alt="your image" />
</form>
Try this:
Html:
<form id="form1" runat="server">
<input type='file' data-val="#blash1" class="imgInp" /> // add class imgInp here
<img height="100" id="blah1" src="#" alt="your image" />
<br>
<input type='file' data-val="#blash2" class="imgInp" />
<img height="100" id="blah2" src="" alt="your image" />
<br>
<input type='file' data-val="#blash3" class="imgInp" />
<img height="100" id="blah3" src="" alt="your image" />
</form>
Jquery:
function readURL(input,img_name) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#'+img_name).attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$(".imgInp").change(function(){
var img_name = $(this).next("img").attr("id");
readURL(this,img_name);
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.