tags:

views:

57

answers:

1

When I refresh page always show you selected, why?

Thanks.

if ($("#users option:selected"))
{
  alert('you selected');
}

<select name = "users" id = "users">
  <option value="0">text</option>
</select> 
+10  A: 

jQuery will always return an object, even if it is empty, so your conditional will always execute regardless of anything being selected or not. Use a check on length instead.

if ($("#users option:selected").length > 0)
Anurag
*length > 0* is a good enough check to make sure the jQuery selector actually returns something. Without knowing what the OP actually wants to check for, this is as good an answer as he's probably going to get. +1 from me. *edited due to comments deleted.*
Andy E
combine this with @Sarfaraz's answer as the first option is selected by default, so add a dummy option at the beginning - `"Select User"` or something. Or remove the default selected option by calling `$(..).removeAttr('selected')` on app startup.
Anurag
@Anurag I don't think it's possible to have a `<select>` element with no `<option>` selected. Even if it's a dummy empty option, it's still an option and if it's showing its "selected" attribute would be `true`. **Unless**, of course, it's a multi-select.
Pointy
@Pointy - I tested a [small script](http://jsfiddle.net/5Mh3a/) which unselects everything in a select list on Chrome/Safari, and Firefox with interesting results. Setting the `selectedIndex` property to -1 works on all three. Removing the `selected` attribute only works on Chrome/Safari. @Andy's comment mentioned setting the `selectedIndex` property to -1 prior to his edit. Don't know how well these fare on IE.
Anurag
What does the UI actually show when you set selectedIndex to -1? I hope it doesn't show one of the options.
Pointy
just shows a blank.
Anurag