November 12th, 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.

  • SejberCze

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