Common Dropdown operation (Get, Set, Add, Remove) using jQuery

DropDown list is a very basic and common control and You might be using either ASP.NET Dropdown list or normal html dropdown list in your project. In this post, I have put together the code examples for all kind of dropdown operation. For example, to get selected value from dropdown, for to set value in dropdown, for to add items to dropdown, for to remove items from dropdown and to enable/disable items in dropdown using jQuery. These little code snippets related to all kind of dropdown operation are quite useful.

I have summarized the code snippets under different sections which are given below.

Get value and text from dropdown list

Get selected option value
Get selected option text
$('#ddlList option:selected').text()
Get dropdown list text
Get selected index
Select first element
$("#ddlList option:first-child").attr("selected","selected");

Set value and selected index

Set selected index
$("#ddlList").get(0).selectedIndex = 3;
Set element by Value
Set element by Text
$('#ddlList option:contains("HTML")').attr("selected","selected");

Add Items to dropdown list

Add item to list in the begining
Add item to list in the end

Remove Items from dropdown list

Remove selected item
$('#ddlList option:selected').remove();
Remove Item by Value
$('#ddlList option[value="4"]').remove();
//This removes items with value 4.
Remove Item by Text
$('#ddlList option:contains("HTML")').remove();
//This removes items with Text HTML.
Remove all items excluding first item
$('#ddlList option:not(:first)').remove();
Remove all items excluding last item
$('#ddlList option:not(:last)').remove();
Clear/Empty drop down
$("#ddlList > option").remove();

Enable/Disable items in dropdown list

Disable item by value in dropdown list
$("#ddlList option[value='3']").attr("disabled","disabled");
//This disables item with value 3.
Disable item by text in dropdown list
$('#ddlList option:contains("HTML")').attr("disabled","disabled");
//This disables item with text "HTML".
Enable item by value in dropdown list
$("#ddlList option[value='3']").removeAttr("disabled");
//This enables item with value 3.
Enable item by text in dropdown list
$('#ddlList option:contains("HTML")').removeAttr("disabled");
//This enables item with text "HTML".

Selection Change Event
$("#ddlList ").change(function()
   /* do something here */

Hope you have find it useful.

Feel free to contact me for any help related to jQuery, I will gladly help you.

Nothing shocks me, I'm a Software Engineer. And I am not young enough to know everything. I live in World Wide Web and from there take care of this website. This website communicates about my work, learning and experience. I believe life is short, and it is for loving, sharing, learning and connecting. So lets connect..