views:

86

answers:

3

i have the following simple script


<input type="button" onclick="document.getElementById('a').innerHTML = '<option>something</option>';"/>    
 <select id="a" style="width: 150px;">
</select>

but it doesn't work in IE. could you tell me why? thanks

A: 

IE doesn't tend to like you doing things that way for such items. Same goes for setting the innerHTML of tables.

You should learn to do things the DOM way....for instance, using createElement ("OPTION"), then appendChild() (first removing children with removeChild() if needed). In general it is way better than innerHTML.

rob
A: 

Use this code:

var optionElement = document.createElement("option");
optionElement.innerHTML = "some text here";

document.getElementById('a').appendChild(optionElement);
Vincent
@Vincent yes, it works, but i use ajax, and in php file i generate ready option list, in that case i can't use appendChild method:(
Syom
+2  A: 

You will be better off having the AJAX script return a JSON object containing the options you want, then using DOM methods to create the option nodes to match them.

If you really must do this with HTML strings, the way to do it is to write a completely new <select> element with the options inside. Then you can copy the information from the <option> nodes into to the select you were originally targeting.

var select= document.getElementById('a');
select.options.length= 0;

var div= document.createElement('div');
div.innerHTML= '<select>'+options+'</select>';
var options= div.firstChild.options;
for (var i= 0; i<options.length; i++) {
    var o= options[i];
    select.options[i]= new Option(o.text, o.value, o.selected);
}
bobince
@bobince thanks man, i was thinking on it whole day.i don't know json at all, maybe you can give a link, there i can read about them?
Syom