you need to reset the input
after prepend call.And jquery
have default element target.so you could use this
instead of event.target
$('[name=photo_input]').change(function(e) {
var imagePath = this.files[0].name;
var imageElement = `
<div class="col-md-4">
<img src="${imagePath}" />
</div>
`;
$('.row').prepend(imageElement);
$(this).val('') // you need to reset input after change event
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row"></div>
<input type="file" name="photo_input" />
This function is working – each image creates element (e.target.files[0].name
is not an image path so you shouldn’t present preview like that).
But only the last state of the input file is being sent to the server.
-
You can use <input type="file" multiple />
then users can pass more than one image to the input – the previous state will still override but you still POST that to a server without additional JS logic.
-
You can create an external array with files, and add files there on change event, but to post them you have to override the default form submit method in JS (because you will be sending the content of the array not the value from the inputs).
I have input type file when i click on that i want to display selected pictures one by one there but right now its working for first time when i click on second time it is not working to add more images.
I want to add multiple pictures.
My Code:-
$('[name=photo_input]').change(function (e) {
var imagePath = e.target.files[0].name;
var imageElement = `
<div class="col-md-4">
<img src="${imagePath}" />
</div>
`;
$('.row').prepend(imageElement);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row"></div>
<input type="file" name="photo_input" />
Answer will be appreciated!
Above code was working good.Its prepend the new image on each time input file change.I think you have mistakenly choose same file on second time.Thats why its not trigger the event .Try with different file on each selection
@prasanth each time file change is working fine but i want to add each time instead of change.