tags:

views:

44

answers:

3

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!

+3  A: 

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

if( $("#players option:selected").is(":first-child") )
{
    alert("Please select a player!");
}

Here's a Working Demo of that in action. add /edit to the URL to see the code

Russ Cam
That pretty much clears things up! Thank you!
zdawg
A: 

I think option 1 will return a set of selected options (there is normally always 1 item selected), and then tests if the first element of that set exists, which it always will. (ie, it does not test if the returned selected option is the first option in the list, but instead gets the list of selected options and checks to see if there are any).

rikh
A: 

The :eq(0) selector gets the first element in a set. Therefore, your element will always match it when you call the is method.

SLaks