I have a select menu of countries (I can't change this server side). One of its options is already selected, based on previous user choice.
I also have a list of country codes (also generated server side) which specifies the countries that should appear in the menu. (Most should be removed.)
I have come up with the following script, and can't see why it doesn't work. I can disable the unwanted countries with
countrymenu.options[i].disabled = true;
but
countrymenu.remove[i];
(which is what I need) does nothing.
Any help would be appreciated.
<html>
<head>
<script type="text/javascript">
function HideCountries()
{
countrymenu = document.checkoutform.country_code;
for (var i = 0; i < countrymenu.length; i++)
{
if (/^ASM|AIA$/.test(countrymenu.options[i].value)==false)
{
countrymenu.remove[i];
}
}
}
window.onload=HideCountries;
</script>
</head>
<body>
<form name="checkoutform">
<select name="country_code" id="country_code">
<option value="AFG">Afghanistan</option>
<option value="ALA">Åland Is.</option>
<option value="ALB">Albania</option>
<option value="DZA">Algeria</option>
<option value="ASM">American Samoa</option>
<option value="AND">Andorra</option>
<option value="AGO">Angola</option>
<option value="AIA">Anguilla</option>
<option value="ATA" selected="selected">Antarctica</option>
</select>
<input type="submit" />
</form>
</body>
</html>
Although you have the remove()
function incorrect, you should also remove items in reverse order, because once an item is removed, indices are shifted.
http://jsfiddle.net/MrPolywhirl/gPY3p/
function hideCountries() {
countrymenu = document.getElementsByName('country_code')[0]
for (var i = countrymenu.length-1; i >= 0; i--) {
if (/^ASM|AIA$/.test(countrymenu.options[i].value) == false) {
countrymenu.remove(i);
}
}
}
window.onload = hideCountries();
This should leave only: