In this tutorial, you will learn how you can remove the dropdownlist or combobox options using JQuery. There will be 5 function examples given, where the options can be removed based on value, selectedindex, specificvalue(contains), selectedindex, and all options.
Firstly remember to include the jquery hosted file by Google.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script> <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.min.js" type="text/javascript"></script>
Below are the five jquery functions:
/**** REMOVE OPTION BASED ON VALUE ****/ function removeBasedOnValue(id, value) { $("#" + id + " > option[value='" + value + "']").remove(); } /**** REMOVE OPTION BASED ON OPTION INDEX ****/ function removeBasedOnIndex(id, value) { $("#" + id + " > option:eq(" + value + ")").remove(); } /**** REMOVE OPTION CONTAINING SPECIFIC VALUE ****/ function removeBasedOnContainValue(id, value) { $("#" + id + " > option:contains('" + value + "')").remove(); } /**** REMOVE SELECTED INDEX ****/ function removeSelectedIndex(id) { $("#" + id + " > option:selected").remove(); } /**** REMOVE ALL OPTIONS ****/ function removeAllOptions(id) { $("#" + id + " > option").remove(); }
This will be the example on how to use it, let's say we have the following html:
<select id="ddNumbers"> <option value="1">Number 1</option> <option value="2">Number 2</option> <option value="3">Number 3</option> <option value="4">Number 4</option> <option value="5">Number 5</option> <option value="6">Number 6</option> <option value="7">Number 7</option> <option value="8">Number 8</option> </select>
Example on how to use the functions based on above dropdownlist.
/** Remove all options **/ removeAllOptions('ddNumbers'); /** Remove option that contains number 4 **/ removeBasedOnContainValue('ddNumbers', '4');