Wednesday, 14 May 2008

Work around for Internet Explorer when dynamically changing Select Option

OK, so quite a common thing to do is update the items in a multiple select box with options sent from the server through some javascript.

And it's very simple.. you just get your response and stick it into the select box with using innerHTML on the select box. Unless you're using IE that is!

IE has a bug where is will remove the first OPTION when using innerHTML. It's only been there since 1999, so I'm sure they'll fix it soon! :P In the mean time check out this blog entry:

Which has good info, or return XML from your server and parse it in the Javascript creating new Options as you go. This is how I did it, adapted slightly from 'Learning Javascript'.

var opsnodes = xmlhttp.responseXML.getElementsByTagName('op');
for(var i = 0; i < opsnodes.length; i++){
var name = value = null;
for(var j = 0; j < opsnodes[i].childNodes.length; j++){
var elem = opsnodes[i].childNodes[j].nodeName;
var val = opsnodes[i].childNodes[j].firstChild.nodeValue;
if (elem == 'value'){
value = val;
name = val;
}//end for j
sel.options[i] = new Option(name,value);
}//end for i
alert('Sorry there was an error');

where sel is the select box.

No comments: