Reputation: 41
Basically I have a form which inside it I have an image box with a file input, now i need to show the the picture choosen from file input and show it in my image box without the form to submit.
i found a tutorial which says:
<!DOCTYPE html>
<html>
<head>
<script>
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
function readURL(input) {
if (input.files && input.files[0]) {
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
alert(input.val());
});
</script>
</head>
<body>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
</html>
but this don't show the select image in my image box.
Upvotes: 0
Views: 872
Reputation: 1
javascript
at Question appears to return expected result. The issue is placement of <script>
element or not utilizing .ready()
. Also, input
is not defined within change
event. You can substitute this.value
for input.val()
within change
event handler as parameter to alert()
call.
Placing <script>
element beneath <form>
element at html
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<form id="form1" runat="server">
<input type="file" id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
<script>
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
function readURL(input) {
if (input.files && input.files[0]) {
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
alert(this.value);
});
</script>
</body>
</html>
using .ready()
with <script>
element remaining as child of <head>
element
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
<script>
$().ready(function() {
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').attr('src', e.target.result);
}
function readURL(input) {
if (input.files && input.files[0]) {
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function() {
readURL(this);
alert(this.value);
});
})
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="file" id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
</body>
</html>
Upvotes: 0
Reputation: 1676
try this sample js
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>
Upvotes: 3