This is weird, im trying to clear my select list and exactly half is being cleared, not everything. Its also every other item which is left behind. I havent included the data here, but just the setup of the select list. The data is 10 items and only 5 are deleted. UniList calls DeleteAll. The first alert prints out ’10’ and the second prints out ‘5’
DID is just document.getelementbyid()
function DeleteAll(string) {
var i;
var list = DID(string);
alert(DID(string).options.length);
for (i = 0; i<list.options.length; i++) {
list[i] = null;
}
alert(list.options.length);
alert("finished deleting");
}
<select size='12' name='UniList' id='UniList' style='width:180px;' onclick=changeuni('UniList','Uni')>
<option value=''></option>
<option value=''></option>
<option value=''></option>
</select>
list.optionsis a HTMLOptionsCollection that is assumed to be live:So with every iteration one item is removed and the document is updated so that
list.optionsand thuslist.options.lengthis updated too. So instead of removing the first, second, third, etc. option of the list you actually remove the first, third, fifth, etc. option.Use
list.options[0]instead to always remove the first option:Or remove the options from behind:
By the way: The HTMLSelectElement has a
removemethod to remove an option by its index: