Nov 12, 2010

jQuery: Common Operations on DropdownList (Combobox)

This post explains how you can perform common operations (like get/set selectedvalue, selectedindex and selectedtext .. etc) of dropdownlist (combobox) using jQuery. Let us take an example to understand:

  <select ID="DropDownList1">
            <option Value="0"> Please Select</option >
            <option Value="val1">First</option >
            <option  Value="val2">Second</option >
            <option  Value="val3">Third</option >
            <option  Value="val4">Fourth and Last</option >
        </select>

1. Selected Value:

To get value of selected item:

$(“#DropDownList1”).val()

To select item from value:

$(“#DropDownList1”).val(“val2”)

It will select “Second” option.

2. Selected Text:

To get text of selected item:

$(“#DropDownList1 option:selected”).text()

Then you think, what would be output of $(“#DropDownList1”). text()?
It will shows Text values of all options.

To select item from text:
$(“#DropDownList1 option:contains(‘Fourth’)”).attr(‘selected’, ‘selected’);

It will select option which has Fourth in the text. If you want to match exact string, you can use filter method.

$(“#DropDownList1 option”).filter(function() {
return $(this).text() == “Fourth and Last”;
}).attr(‘selected’, ‘selected’);

3. Selected Index:

To get index of selected item:

$(‘#DropDownList1’).get(0).selectedIndex

To select item from index:

$(‘#DropDownList1’).get(0).selectedIndex = 3;

It will select ‘Third’ option.

4. Create Dynamic Dropdown List

Easy way is to create html string of dropdownlist and add it in container.

$('body').append('<select><option...</option></select>');

You can split in 2 steps: first assign dropdownlist html string to variable and use the variable for further operations.

5. Add option dynamically:

To add all options in blank dropdownlist

var str = “<option>...</option>….<option>..</option>” 
$('#DropDownList1').html(str);

To add new option:

$('#DropDownList1').
          append($("<option/>").
          attr("value",'val5').
          text('Fifth'));

It will add ‘Fifth’ option with ‘val5’ value.

Hope, It helps. If you have other common operations, Please share it in below comment box.

2 comments

  1. Hi,
    I have a select list dynamically filled on form load,
    my requirement is that suppose I have four elements in select list
    once i select any element and press clone button it should create clone list without selected element …. I am trying hard but I did cloning and also removal of selection from list but after removal when it is cloned the value of old and new cloned list is reset to the first element, which i dont want….please help

  2. The fifth example didn’t work.
    That’s work good:
    $(‘#DropDownList1’).
    append(
    $(”).
    val(‘value’).
    text(‘text’)
    );

Leave a Reply to Muhammad Saeed Cancel reply

Your email address will not be published. Required fields are marked *