I have a ‘select’ drop-down with a list of players’ names, which by default has the first item–also an empty item, selected. I would like to do a simple test on whether this item is selected when the user clicks a button below.
I came across two possible solutions:
1)
if( $("#players option:selected").is(":eq(0)") )
{
alert("Please select a player!");
}
and
2)
if( $("#players option:eq(0)").is(":selected") )
{
alert("Please select a player!");
}
Solution #2 works perfectly, but #1 always returns true. Does anyone know of a technical reason or limitation on why this is?
Thanks for your replies!
To answer why number 1 is always true, it’s because 1 and 2 do slightly different things.
Solution #1 says “get me the selected
<option>and then check if it’s in the first position in the wrapped set”, which it always will be (you can have only one selected option at a time).Solution #2 says “get me the first
<option>and then tell me if it’s selected”, which it won’t be if any other<option>other than the first is selected.EDIT:
I think what you’re looking for in Solution #1 is the following
Here’s a Working Demo of that in action. add /edit to the URL to see the code