0

addEventListener for input file select in IE 9 and 10 should trigger after the file selection but it triggers after the second time for file select, that means for the first time if no files are selected then for first select it wont trigger and after that for every file selection the listener event triggers (if different file is selected). My code snippet:

HTML

<input type="file" name="imagefile" id="upload">

JavaScript

var file = document.getElementById("upload");
file.addEventListener("change", handlefileselect, false);

function handlefileselect(event) {
    alert("file selected");
}

The code runs fine in Firefox and Chrome but has a problem with IE.

Ry-
  • 218,210
  • 55
  • 464
  • 476
PRASANTH
  • 695
  • 3
  • 15
  • 33

3 Answers3

4

Old IE versions does not support .addEventListener() method, it has a .attachEvent() method instead to add events to elements.

Use the following addEvent method

function addEvent(evnt, elem, func) {
   if (elem.addEventListener)  // W3C DOM
      elem.addEventListener(evnt,func,false);
   else if (elem.attachEvent) { // IE DOM
      elem.attachEvent("on"+evnt, func);
   }
   else { // No much to do
      elem[evnt] = func;
   }
}

var file = document.getElementById("upload");
addEvent('change', file, handlefileselect)
Community
  • 1
  • 1
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • Got it.Thanks.. but Why iam getting this late response – PRASANTH Apr 20 '13 at 05:37
  • Means for first file selection the change event function wont execute but after that for every file selection the event triggers what is the reason. It is happening for me for both ie 9 and 10. – PRASANTH Apr 20 '13 at 05:41
3

You should use attachEvent function for IE.

file.addEventListener ? file.addEventListener("change", handlefileselect, false) : file.attachEvent("onchange", handlefileselect);
Jack
  • 1,892
  • 1
  • 19
  • 23
1

try to use this, I didn't check but most of the IE problems were resolved with this tag in the header part

<meta http-equiv="X-UA-Compatible" content="IE=edge"> 
kumar
  • 1,796
  • 2
  • 15
  • 37