I have 4 file inputs that I want them trigger upload proccess when their value is changed. I mean when you select a picture and click open on select image dialog, the script to upload the picture be triggered. I've used onchange event but I think this is not the right event:
JS:
$("input[type=file]").on('change',function(){ alert(this.val());//I mean name of the file });
HTML:
<div class="form-group col-md-11 col-md-offset-1"> <input type="file" name="photos[]"> <input type="file" name="photos[]"> <input type="file" name="photos[]"> <input type="file" name="photos[]"> </div>
What should I do?
The only way to set the value of a file input is by the user to select a file. This is done for security reasons. Otherwise you would be able to create a JavaScript that automatically uploads a specific file from the client's computer.
How it works: First, select the <input> element with the id message and the <p> element with the id result . Then, attach an event handler to the input event of the <input> element. Inside the input event handler, update the textContent property of the <p> element.
Definition and Usage The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.
The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.
The OnChange
event is a good choice. But if a user select the same image, the event will not be triggered because the current value is the same as the previous.
The image is the same with a width changed, for example, and it should be uploaded to the server.
To prevent this problem you could to use the following code:
$(document).ready(function(){ $("input[type=file]").click(function(){ $(this).val(""); }); $("input[type=file]").change(function(){ alert($(this).val()); }); });
Use the files
filelist of the element instead of val()
$("input[type=file]").on('change',function(){ alert(this.files[0].name); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With