Pages

Search This Blog

Tuesday, 7 January 2014

jQuery to loop through a DropDown and change the Selected Index

In this example we will see how to loop through all items in a DropDown (HTML Select) and change the Selected Index when a particular condition is met. There will be cases where an index change has to be triggered explicitly which in turn loads the data for second DropDown. These expectations will be met in this post.

HTML Select Element:

<select id="ddlCars" runat="server">
     <option>Volvo</option>
     <option>Saab</option>
     <option>Mercedes</option>
     <option>Audi</option>
</select>


jQuery to change Selected Index and trigger change event

var carToBeSelected = "Mercedes";
$('#ddlCars option').each(function () {
                 var item = $(this).val().toString();
                 if (item == carToBeSelected)

                {
                     $(this).attr("selected", "selected");  //select the current item                                     $('#ddlCars').trigger('change');  //explicit trigger of change event                                    
                 }
                 index++;

});

When any change event is associated with the DropDown that piece of code will be executed when trigger('change') is triggered.

When all the items in a DropDown is associated with a value attribute then the following one line of code will do the trick.

<select id="ddlCars">
     <option value="volvo">Volvo</option>
     <option value="saab">Saab</option>
     <option value="mercedes">Mercedes</option>
     <option value="audi">Audi</option>
</select>


$('#ddlCars').val("mercedes");

No comments:

Post a Comment