admin管理员组

文章数量:1384812

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.

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.

Share Improve this question edited Apr 20, 2013 at 5:17 Ry- 225k56 gold badges493 silver badges499 bronze badges asked Apr 20, 2013 at 5:10 PRASANTHPRASANTH 7053 gold badges15 silver badges33 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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)

You should use attachEvent function for IE.

file.addEventListener ? file.addEventListener("change", handlefileselect, false) : file.attachEvent("onchange", handlefileselect);

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

本文标签: javascriptListen to change event in Internet ExplorerStack Overflow