Common Dropdown operation (Get, Set, Add, Remove) using jQuery
I have summarized the code snippets under different sections which are given below.
- Get value and text from dropdown list
- Set value and selected index in dropdown list
- Add Items to dropdown list
- Remove Items from dropdown list
- Enable/Disable items in dropdown list
- Selection Change Event
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 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 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:
$("#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.