1

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

2

4 Answers 4

2

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);
}
Sign up to request clarification or add additional context in comments.

1 Comment

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?
1

Or simply use jQuery and html() instead of innerHTML...

So...

$("#a").html("<option>Whatever</option>");

Works great in all browsers for all objects!

Comments

0

Use this code:

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

document.getElementById('a').appendChild(optionElement);

1 Comment

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:(
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.