I have an HTML select element with some countries as the options.
<select id="countryLocation" class="selectCountryPrefix enablePartialForm" onchange="document.locationchangeform.submit()" name="country">
<option selected="selected" disabled="disabled" value="">Select country</option>
<option class="showTos-AU" title="+61" value="AU">Australia</option>
<option class="showTos-CA" title="+1" value="CA">Canada</option>
<option class="showTos-CL" title="+56" value="CL">Chile</option>
<option class="showTos-DK" title="+45" value="DK">Denmark</option>
<option class="showTos-EE" title="+372" value="EE">Estonia</option>
<option class="showTos-FI" title="+358" value="FI">Finland</option>
<option class="showTos-GR" title="+30" value="GR">Greece</option>
<option class="showTos-HU" title="+36" value="HU">Hungary</option>
<option class="showTos-IE" title="+353" value="IE">Ireland</option>
<option class="default showTos-LV" selected="selected" title="+371" value="LV">Latvia</option>
<option class="showTos-TW" title="+886" value="TW">Taiwan</option>
</select>
I want to remove all of the options that have a country code not equal to “TW”. So far this is my code:
YAHOO.util.Event.addListener(window, "load", function() {
var E = YAHOO.util.Event;
var D = YAHOO.util.Dom;
var opts,
select,
i;
select = D.get('countryLocation');
opts = select.options;
for (i=0; i< opts.length-1; i++){
if (opts[i].value !== ""){
if (opts[i].value !== "TW"){
select.remove(i);
}
}
}
})
it only works on some of the options – I’m guessing that because it’s removing them by index then the indexes are changing after each one is removed. What I really want it something like the jQuery .each() function.
How can I do this either in YUI or just plain JS?
Another approach (in regard to Brant Olsen’s answer) is to iterate backwards:
I usually go with this approach when deleting objects from an array (within an iteration).