Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE removes option tags created with javascript

So I have this following code that works great for every browser I've tested so far, except IE

var array = eval( '(' + xmlHttp.responseText + ')' );
var html = '';

for(var key in array)
{
    html += '<option value="' + key  + '">' +array[key] + '</option>';
}
alert(html);
document.getElementById('countries').innerHTML = html;

The problem stands at the .innerHTML. The alert prints the data as it should be, but the inner strips the tag and I end up with words in a row.

So, any ideas how to possibility fix that issue?

like image 210
Alex Avatar asked Feb 13 '26 22:02

Alex


1 Answers

It's a known issue that IE doesn't let you use .innerHTML to set option elements in a select.

You should be creating elements using DOM methods instead.

var fragment = document.createDocumentFragment();

for(var key in array) {
    var opt = fragment.appendChild(document.createElement("option"));
    opt.value = key; 
    opt.text = array[key];
}

document.getElementById('countries').appendChild(fragment);

And if array is an actual Array, then use for instead of for-in in JavaScript.

And if you need to empty the select first, you can do that with .innerHTML = "", or better, with a loop:

var sel = document.getElementById('countries');
while (sel.firstChild)
    sel.removeChild(firstChild);

sel.appendChild(fragment);
like image 108
I Hate Lazy Avatar answered Feb 16 '26 11:02

I Hate Lazy