show chosen image immediately.

In this tutorial I’ll show you a small Javascript code which you can use to add an image and show it immediately.

First things first. Adding the input and the image tag.

[code]
<input type=”file” id=”file” name=”file” onchange=”readURL(this);” required><span id=”filename”></span>
<img src=”” alt=”” id=”imediateImage” class=”img-responsive”>

[/code]

here we have to make sure we added the onchange attribute and adding the readURL(this) function.

Then we just add the javascript.

[code]

//Show image imediately
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(‘#imediateImage’)
.attr(‘src’, e.target.result);
};
reader.readAsDataURL(input.files[0]);
}
}

[/code]

the added js takes the input tag with the onchange attribute on it and looks for an image, once the image is added it shows it to the image tag down below with the id on immediateImage.

if you use another id or don’t like this one than you can do it but changing the id on both the img tag and on the js.

 

CategoriesUncategorized

Leave a Reply

Your email address will not be published. Required fields are marked *