IMG-LOGO

How to remove combobox items using JQuery?

andy - 02 Jun, 2013 7858 Views 0 Comment

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');

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles

Become a jquery expert in just 10 minutes.

Completely new to JQuery script Don t worry you are not alone We have summarize a list of tips for newbie to learn JQuery faster The best way to strength your JQuery skills is by testing our tips directly in ...