Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
132
rated 0 times [  136] [ 4]  / answers: 1 / hits: 15891  / 15 Years ago, fri, july 17, 2009, 12:00:00

As far as I can tell this only is only broken in Internet Explorer. I have a script that creates multiple dynamic <select> elements and adds an onchange event for them. The onchange event fires in Firefox with no problem but in Internet Explorer it never fires. Using Developer Toolbar I see the DOM has the correct event listed, it just never fires. I've boiled down the problem to the following code:



<html>
<head>
<script language=javascript>
function addSelect() {
var se = document.createElement('select');
se.setAttribute(onchange, alert('Dynamic'));
se.options[0] = new Option(1, 1);
se.options[1] = new Option(2, 2);
se.options[2] = new Option(3, 3);
se.options[3] = new Option(4, 4);
var plh = document.getElementById(ph);
plh.appendChild(se);
}
</script>
</head>
<body onload=addSelect()>
<select name=something onchange=alert('Static')>
<optgroup label=set1>
<option value=1>1</option>
<option value=2>2</option>
</optgroup>
<optgroup label=set2>
<option value=3>3</option>
<option value=4>4</option>
</optgroup>
</select>
<div id=ph>
</div>
</body>
</html>


The static alert message comes up fine, but the dynamic one doesn't do anything in Internet Explorer. I'm nearly positive I've seen this work elsewhere, but I can't seem to find other examples. Does anybody see/know of a way to get this to work?


More From » html

 Answers
14

Change:



se.setAttribute(onchange, alert('Dynamic'));


to:



se.setAttribute(onchange, function(){alert('Dynamic')});


or even shorter:



se.onchange = function(){alert('Dynamic')};

[#99105] Monday, July 13, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;