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

$('#ddlList').val()

Get selected option text

$('#ddlList option:selected').text()

Get dropdown list text

$('#ddlList').text()

Get selected index

$("#ddlList").get(0).selectedIndex;

Select first element

$("#ddlList option:first-child").attr("selected","selected");

DEMO:

Set value and selected index

Set selected index

$("#ddlList").get(0).selectedIndex = 3;

Set element by Value

$("#ddlList").val(5);

Set element by Text

$('#ddlList option:contains("HTML")').attr("selected","selected");

DEMO:

Add Items to dropdown list

Add item to list in the begining

$("#ddlList").prepend("
");

Add item to list in the end

$("
").appendTo("#ddlList");

DEMO:

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").empty();
//OR
$("#ddlList > option").remove();

DEMO:

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".

DEMO:

Selection Change Event

$("#ddlList ").change(function()
{
   /* do something here */
});

DEMO:

Hope you have find it useful.

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



Responsive Menu
Add more content here...