Using jquery to find a selected option in a drop down list

If you have a drop down list in your HTML form, automatically setting the index isn't a slam dunk. jQuery doesn't make it intuitive.


How to test if an option has been selected:

Option #1 - assign an id to the options in your select input. This makes it easier to compare the selected index with your target option.

if ($("#my_select option:selected").attr("id") == "id_of_the_desired_option")
{
   ...
}

// or

if ($("#id_of_the_desired_option").attr("selected") == "selected")
{
   ...
} 

Option #2 - look at the specific value of the selected option. I don't like this because now you are hardcoding values into the code, and values can change easily, breaking your code. But it's an option, nonetheless.


if ($("#my_select option:selected").val() == "this is the option value")
{
   ...
}



No comments:

Post a Comment