InnerHTML IE 8 doesn't work properly? Resettin

2019-07-24 19:29发布

问题:

Yeah this works in FF and Chrome, but for some reason wont work in IE 8. I'm using a radio button to clear a section of a form.. that section is a select box, but I don't want to leave the area empty - instead I want to reset it to what it was when the page loaded. At the moment IE8 is just leaving me with an empty small select box.

Html:

<select id="city_select" disabled="true" name="location_id" onchange="show_search_button();"><option selected>Select your city</option> </select>

Javascript:

document.getElementById('city_select').innerHTML = "<option selected>Select your city</option>";

I've also tried using location_id instead of city_select in the javascript but to no avail.. innerText and innerContent dont work either.. though the inner.HTML works in IE8 for an earlier function, but that isnt trying to innerHTML into a form. Does anybody know why this works in Chrome and FF but not IE8? and is there a solution to this? Any help appreciated thanks!

回答1:

Try this:

document.getElementById('city_select').options.length = 0;

Then create a new option and push it onto the options array of the select. The options are a tricky bit that don't behave like other markup.

Edited to show how to create an option:

var sel = document.getElementById('city_select').options.length = 0;
var opt = document.createElement('option');
opt.value = "Select Your City";
sel.options.push(opt);
sel.selectedIndex = 0;


回答2:

There are supposed to be 4 way of assigning new options to a select element. Some work in some scenarios and others work in others. Look here - How to Add options to <SELECT>, in IE Windows Mobile 5

For me, Robusto's solution didn't work due to three reasons:

1) sel variable in the first line is assigned document.getElementById('city_select').options.length = 0; instead of simply holding the select element (for later use in 4th and 5th line) and then deleting options in a next line, like this:

var sel = document.getElementById('city_select');
sel.options.length = 0;

2) the 4th line sel.options.push(opt) (or later suggested sel.options[0] = opt) throws an Object doesn't support this property or method error. Instead use this:

sel.appendChild(opt);

3) apart from assigning values to options you must also assign text to display. You do it like this:

opt.innerText = "Select Your City - displayed";

Therefore, to sum up the whole piece:

var sel = document.getElementById('city_select');
sel.options.length = 0;
var opt = document.createElement('option');
opt.value = "Select Your City";
opt.innerText = "Select Your City - displayed";
sel.appendChild(opt);
sel.selectedIndex = 0;