Reputation: 7688
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?
Upvotes: 3
Views: 431
Reputation: 23149
var select = document.getElementById('countries'); // assuming this is your <select>
for (var key in array) {
var option = document.createElement('option');
option.value = key;
option.text = array[key];
select.appendChild(option);
}
Upvotes: 3
Reputation: 48761
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);
Upvotes: 5