Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

on change event for file input element

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?

like image 327
Ramin Omrani Avatar asked Nov 27 '13 13:11

Ramin Omrani


People also ask

How do I change the input value of a file?

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 do you add an input to an event?

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.

What is the use of Onchange event of select 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.

What is Onchange input?

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.


2 Answers

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());     }); }); 
like image 166
Humberto Corrêa Avatar answered Sep 20 '22 05:09

Humberto Corrêa


Use the files filelist of the element instead of val()

$("input[type=file]").on('change',function(){     alert(this.files[0].name); }); 
like image 26
techfoobar Avatar answered Sep 23 '22 05:09

techfoobar