3

The code below dynamically creates a file input once my custom button is clicked generating a file input with a name of photo[] and an id of photo'x' (x as a variable). The code is working fine with all the browsers except the almighty IE. In IE i can click my custom upload button add a file and when i submit the form, the file input will be cleared. It will submit the form but the file input would be blank. But it works well with other browsers.

is this a bug? or a security thingy? if it is, how can i fix this problem?

var x = 0;
addFile = function(addFileButton) {
    var form = document.getElementById('form');
    var box = document.createElement('input');
    box.type = 'file';
    box.name = 'photo[]';
    box.id = 'photo' + x;
    box.style.cssText = 'position:absolute; top:-200px;';
    box.onchange = function() {
        checkFileDup(this.value, x - 1);
    };
    form.appendChild(box);
    jQuery("#photo" + x).trigger('click');
    x++;
}
Esailija
  • 138,174
  • 23
  • 272
  • 326
Kiel
  • 483
  • 3
  • 5
  • 18
  • You're using `jQuery` only for triggering a `click` event? – Andreas Jul 26 '12 at 07:44
  • Yes, will that affect the code? – Kiel Jul 26 '12 at 07:46
  • It would make it easier - that's all :) – Andreas Jul 26 '12 at 10:22
  • It's a security feature. To workaround it, you have add box.onclick = function... to capture the text during the click events in IE, so you can validate it before the change event. – Paul Sweatte Jul 31 '12 at 01:45
  • @PaulSweatte thanks for ur reply. Actually I can already validate everything but the only problem i have is when i submit the form, the file input clears its content as a result the submitted file is gone any work around with this issue? if box.onclick = function? what should i do inside the function? sorry i'm still a newbie with javascript and jquery. Thanks – Kiel Jul 31 '12 at 02:42
  • You have to copy the file value to a dummy input field and layer that over the file input using absolute positioning to [fake it](http://stackoverflow.com/questions/2034826/how-to-hide-text-field-in-html-file-upload). – Paul Sweatte Jul 31 '12 at 14:24
  • @PaulSweatte thanks paul i did your advice but i does not get the file from the user. It only gets the file path. :( – Kiel Aug 06 '12 at 02:49
  • Try different selectors such as jQuery("input[type='file']").val() or add a class to the input and reference by class name. There's a [bug](http://bugs.jquery.com/ticket/11983) in IE which makes the event handlers inconsistent, so you have to capture both the change and the click events to workaround it. – Paul Sweatte Aug 06 '12 at 17:30

1 Answers1

5

It is a issue of IE, input[type=file] created via javascript are not submitable through form.

My solution is to make a bundle of hidden input[type=file] elements in the page and make them visible when required.

otakustay
  • 11,817
  • 4
  • 39
  • 43