Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternate to onchange event in <input type='file' />

Seems really a simple thing but can't figure it out. I've been using the onchange event on <input type=file /> element and it works well. Once the user browses and selects a file, I get the path and upload it using a my custom js function.

The problem is this doesn't work if a user selects the same file twice in a row, the onchange doesn't fire (which makes sense since nothing changed) but in my case it's important for me to capture that event too, get the path and upload.


(Similar to Clearing <input type='file' /> using jQuery, not sure if I should resolve this as duplicate)

like image 494
Yasir Laghari Avatar asked Jan 25 '10 16:01

Yasir Laghari


People also ask

What can I use instead of Onchange?

oninput. Another JavaScript event that is quite similar to onchange is oninput . The difference is that oninput is triggered every time the value of an element changes even while it still is in focus.

Can I use Onchange in input?

That's why onchange is used with form controls, like input, select, checkbox, radio buttons, etc. The Javascript listens for user input and fires this event whenever a value gets updated. The onchange event attribute fires the event when the element loses focus.

What is the difference between Oninput and Onchange?

Definition and Usage 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, after the content has been changed.

How do I change the default input type file?

You can't. 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.


2 Answers

You can just remove the input and create an identical one with javascript - the new one will be empty.

(edited answer to be straight to the point, comments are irrelevant now)

like image 78
raveren Avatar answered Sep 29 '22 04:09

raveren


You could have the choose file button clear the contents of the input onclick, that way even even if they choose the same file your event will still trigger. Of course, then your onchange handler will have to check for blank values, but it should probably be doing something similar or more anyway if it's going to use that value to upload a file...

like image 32
tfwright Avatar answered Sep 29 '22 05:09

tfwright