jQuery and Option Inputs

The input type “option” is a drop down list. At some time you may need to find the value of the current or new selected value, you may also need to change the selected value. This tutorial is split up into small sections so just find the code your looking for and thank me later.

Basic structure of a Select Option Html tag.

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

Getting selected Value

$('select').attr("value");

Getting selected Value on change

$('select').change(function(){
alert($(this).attr("value"));
});

Getting selected Text on change

$('select').change(function(){
alert($('select :selected').text());
});

Changing Selected Option

This Code will find the option with a value of “audi” and select is. The code loops through the Select’s children (option tags) untill it finds a child with a curtain attribute. Once a match is found, it then gives the option the selected attribute.

$('select option').each(function(){
if($(this).attr("value") =="audi")
{
$(this).attr('selected','selected');
}
});