Image 01 Image 02

0
Posted on 28th February 2009 by Matt

I have recently had a scenario where i have needed to set the selected=”selected” parameter of a dropdown box using JQUERY based on data from a database.

The scenario:

When the user decides to edit a job I need the current data to fill in the text boxes and other input fields. One of which is a dropdown list. I need to make sure that the selected option is the option that is saved in the database.

For example a dropdown box of job types:

<select id="jobtype">
 <option value="1">Job Type 1</option>
 <option value="2">Job Type 2</option>
 <option value="3">Job Type 3</option>
 <option value="4">Job Type 4</option>
</select>

Then the JQUERY to loop through and add the “selected” attribute to appropriate option:

$("#jobtype option").each(function(i){
 if($(this).val() == data.jt){
  $(this).attr("selected", "selected");
 }
});

Note: data.jt is response from an $.ajax call in JSON format.

What it does:

We use the .each function to loop through all of the options within the jobtype select dropdown until the value of on of the options equals the value of data.jt.

Example:

If    data.jt = 2

Then the select code would end up looking like this:

<select id="jobtype">
 <option value="1">Job Type 1</option>
 <option value="2" selected="selected">Job Type 2</option>
 <option value="3">Job Type 3</option>
 <option value="4">Job Type 4</option>
</select>

bookmark bookmark bookmark bookmark bookmark bookmark bookmark bookmark