Using jQuery, how do you check if there is an option selected in a select menu, and if not, assign one of the options as selected.
(The select is generated with a maze of PHP functions in an app I just inherited, so this is a quick fix while I get my head around those :)
lencioni's answer is what I'd recommend. You can change the selector for the option
('#mySelect option:last')
to select the option with a specific value using "#mySelect option[value='yourDefaultValue']
". More on selectors.If you're working extensively with select lists on the client check out this plugin: http://www.texotela.co.uk/code/jquery/select/. Take a look the source if you want to see some more examples of working with select lists.
You guys are doing way too much for selecting. Just select by value:
This question is old and has a lot of views, so I'll just throw some stuff out there that will help some people I'm sure.
To check if a select element has any selected items:
or to check if a select has nothing selected:
or if you're in a loop of some sort and want to check if the current element is selected:
to check if an element is not selected while in a loop:
These are some of the ways to do this. jQuery has many different ways of accomplishing the same thing, so you usually just choose which one appears to be the most efficient.
I already came across the texotela plugin mentioned, which let me solve it like this: