Making use of the API Filereader (English), you can read the address on input
of the kind file
and collect the binary data and then inject it into the page:
Function
In the function below, we are reading the content of input
of the kind file
and after its completion we create a new DOM element img
to which we assign the data read. Finally, we attach the element to the current page, right after the input
in question.
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img = $('<img/>').attr('src', e.target.result);
$(input).after($img);
}
reader.readAsDataURL(input.files[0]);
}
}
Your practical case
For your practical case, in addition to the function above, you need a small change to the code you have, so that the use of the API is also carried out on the elements you create dynamically.
Where are you attaching the event change
:
$('input[type=file]').on("change", function(){
verificaMostraBotao();
});
We will change to a delegation, in this case from the body
:
$('body').on("change", "input[type=file]", function(){
verificaMostraBotao();
readURL(this);
});
Thus ensuring that new input
created by your function can preview the chosen file.
Final Code
All the code together is as seen below and in Jsfiddle:
Example working on Jsfiddle
HTML
<input type="file">
<input type="button" class="hide" value="Adicionar outro">
jQuery
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$img = $('<img/>').attr('src', e.target.result);
$(input).after($img);
}
reader.readAsDataURL(input.files[0]);
}
}
function verificaMostraBotao() {
$('input[type=file]').each(function(index){
if ($('input[type=file]').eq(index).val() != "")
$('.hide').show();
});
}
$('body').on("change", "input[type=file]", function() {
verificaMostraBotao();
readURL(this);
});
$('.hide').on("click", function() {
$(document.body).append($('<input />', {type: "file" }).change(verificaMostraBotao));
$('.hide').hide();
});
Function credits readURL
, in its simplest form, for @Ivan Baev on SOEN in this answer.
I see you’re following that example you asked yesterday ;)
– Paulo Roberto Rosa
Yes @Pauloroberto (Y)
– Jefferson Alison
Good!! I advise you to use plugins, for these situations because plugins help reduce development time... IE, you will have more time to focus on the business rule of your project... In your case you can use the ezdz jquery
– Cristiano Gil