views:

177

answers:

2

I have these dynamically added file inputs, that I then use a jQuery 'Ajax' file upload plug-in with. I'd like the upload to start once the input value has been 'changed'. However, Internet Explorer doesn't seem to respect the onchange event like other browsers. How can I do this?

Here is, more or else, the code that is affected:

var html = $('<div class="add_input"><input type="file" name="file"/></div>').change(submit);
$('#add_inputs').prepend(html);
+2  A: 

You could just replace the above with something along these lines

var html = $('<div class="add_input"><input type="file" name="file"/></div>');
$('#add_inputs').prepend(html);
$("div.add_input > input[name='file']").change(submit);

or

var html = $('<div class="add_input"><input id="filer" type="file" name="file"/></div>');
$('#add_inputs').prepend(html);
$("#filer").change(submit);
jitter
A bit more explanation: the HTML `<div>` element doesn't support the `change` event. Only the `<input>` element does. You're actually also interested in the change of the input. So you need to apply it on the `<input>` element.
BalusC
thanks, that makes a whole lot of sense!
mikeycgto
oddly enough, that bit of code worked in Firefox... go figure :)
mikeycgto
Seems that some browsers nonetheless support change event for `div`'s. Check http://jsbin.com/udake if your browser shows the alerts when clicking the buttons or not. It does for me in Opera 10.01
jitter
It's the event bubbling as bob has nicely explained in the other answer.
BalusC
+1  A: 

When you create elements from HTML in jQuery, the returned handle references the outermost element(s), so you're putting the change event handler on the <div>, not the <input>.

This works nonetheless in most browsers because in the DOM Level 2 Events specification, the change event ‘bubbles’ up the document to inform its parents when it changes, so an event handler on <div> will get informed of any changes on any of its child <input>s. However IE has its own event model in which change does not bubble.

An alternative:

($('<input type="file" name="file" />')
    .change(submit)
    .prependTo('#add_inputs')
    .wrap('<div class="add_input"></div>')
);
bobince