views:

878

answers:

4

Seems really a simple thing but can't figure it out. I've been using the onchange event on 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.

Edit

(Similar to http://stackoverflow.com/questions/1043957/clearing-input-typefile-using-jquery, not sure if I should resolve this as duplicate)

A: 

Is this behavior only present in IE? If so, it may be related to this issue:
http://stackoverflow.com/questions/1637503/jquery-change-event-on-select-not-firing-in-ie/
In essence: You may need to check for onClick instead.

Daniel
Thanks Daniel tried OnClick but it's called before the user selects the file, so no use :(
Yasir Laghari
+1  A: 

There really isn't any way to fix that. If you add any other listener or timer, then you will potentially upload the file even when the user doesn't want it to (eg, with an onclick). Are you sure uploading the same file can't be done in another way? What about clearing the input once the upload has started (or replace it with a new input if you can't clear it).

Marius
Yep replacing it worked! Thanks MariusFound the solution here : http://stackoverflow.com/questions/1043957/clearing-input-typefile-using-jquery
Yasir Laghari
+3  A: 

One way that first comes to my mind, change (or empty) the text in the input once you do your JS magic so any change registers as such.

Edit, accepted answer is: You can just remove the input and create one with javascript - the new one will be empty for sure

Raveren
The text is a read-only field, I don't think I can empty it out?
Yasir Laghari
The read-only restriction is for users only - if I get what you're saying, in other case you can just remove the input and create one with javascript - the new one will be empty for sure.
Raveren
Thanks Raveren .replaceWith() worked!
Yasir Laghari
Please accept my answer if it worked.
Raveren
+1  A: 

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...

floyd
basically what I said :]
Raveren
Thanks guys but isn't the value field read-only. I don't think I can change it's value empty?
Yasir Laghari
Do you have other inputs in the form? If not, you can just reset the form.
floyd
Reset() may work but I think the .replaceWith is a cleaner solution (since the chances of side effects are less)
Yasir Laghari