Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding option elements using .innerHTML in IE

I have a txt variable that contains my html string that I need to set for a drop down list. The code works fine in all the other browsers except for IE. The basic code is shown below.

while loop with some more code

document.getElementById('theSelector').innerHTML = txt;

where 'theSelector' is the id of my select element for my form

So basically IE poops out and doesn't generate my list. I'll post my webpage below if you'd like to look at the source and everything that I'm doing. If you want to see how the site should function just run it in another browser that's not ie.

http://1wux.com/Resume/signUp.html

like image 960
Dr.Knowitall Avatar asked Dec 19 '11 05:12

Dr.Knowitall


People also ask

How do I add something to innerHTML?

To append using the innerHTML attribute, first select the element (div) where you want to append the code. Then, add the code enclosed as strings using the += operator on innerHTML.

Can I add HTML tags in innerHTML?

The Element property innerHTML gets or sets the HTML or XML markup contained within the element. To insert the HTML into the document rather than replace the contents of an element, use the method insertAdjacentHTML() .


Video Answer


2 Answers

Based on your comment that it isn't generating your list, and Jared's comment that you're trying to add options, try something like this:

var list = document.getElementById('theSelector');
var newOp = document.createElement("option");
newOp.text = "Txt";
newOp.value = "1";
list.options.add(newOp);

EDIT

Per Jared's comment, the following may offer you a bit of a performance advantage:

list.options[list.options.length] = newOp;
like image 178
Adam Rackis Avatar answered Sep 24 '22 01:09

Adam Rackis


As others have mentioned, this is a bug in all version of IE. I would use @AdamRackis's solution, but if you must build your HTML with string, the only workaround seems to be use outerHTML and include your <select> in the string.

Demo: http://jsfiddle.net/ThinkingStiff/TWYUa/

HTML:

<select id="select"></select>

Script:

var options = '<select id="select"><option>one</option><option>two</option></select>';
document.getElementById( 'select' ).outerHTML = options;
like image 36
ThinkingStiff Avatar answered Sep 24 '22 01:09

ThinkingStiff