Using jQuery to remove select options

For times when you would like to remove select options based on the selected option in a different select, jQuery allows a simple option. In my example, I have a select control that the user uses to select their country and then an additional select control for selecting membership types. The membership types are based on on different groups of countries, so it is situation where you will want to remove the options that do not apply to the selected country value.

The first step is to load the jQuery library. I typically load them from the google hosted libraries. Here is the source for your script tag.

src="text/javascript" href="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"

Next, the code that will remove options. The country select in this example is named strCountry and the membership type select is named membercategory.

$(document).ready(function() {<br />

//copy the membercategory select, so we can easily reset it<br />

var selectClone = $('#MemberCategory').clone();   <br />
$('#strCountry').change(function() {<br />
var val = ($(this).val());<br />

//reset the second select on each change<br />

$('#MemberCategory').html(selectClone.html())<br />
switch(val) {<br />

//if United States is selected remove Overseas and Canadian Member Types<br />

case "UNITED STATES":<br />
case "AMERICAN SAMOA":<br />
case "GUAM":<br />
case "NORTH MARIANA ISLANDS":<br />
case "PUERTO RICO":<br />
case "VIRGIN ISLANDS":<br />
case "VIRGIN ISLANDS US":<br />
$("#MemberCategory option[value='IC']").remove();<br />
$("#MemberCategory option[value='FC']").remove();<br />
$("#MemberCategory option[value='DC']").remove();<br />
$("#MemberCategory option[value='SC']").remove();<br />
break;<br />

//if CANADA or MEXICO is selected remove Overseas and US Types<br />

case "CANADA":<br />
case "MEXICO": <br />
$("#MemberCategory option[value='IO']").remove();<br />
$("#MemberCategory option[value='FO']").remove();<br />
$("#MemberCategory option[value='DO']").remove();<br />
$("#MemberCategory option[value='SO']").remove();<br />
$("#MemberCategory option[value='I']").remove();<br />
$("#MemberCategory option[value='F']").remove();<br />
break;<br />
default: <br />
$("#MemberCategory option[value='IC']").remove();<br />
$("#MemberCategory option[value='FC']").remove();<br />
$("#MemberCategory option[value='DC']").remove();<br />
$("#MemberCategory option[value='SC']").remove();<br />
$("#MemberCategory option[value='I']").remove();<br />
$("#MemberCategory option[value='F']").remove();<br />
break;<br />
}<br />
});<br />
$("#strCountry").change()<br />

// $('#strCountry').trigger('change');v

});<br />

The change function at the end ensures that the script runs when the form is loaded with a country already selected.

Comments

Write your comment

(it will not be displayed)

Leave this field empty: