views:

77

answers:

4

Hi,

I've googled and tried a number of ways to do this but none work for me so far. What I am looking for is quite simple: I want to be able to tell whether a dropdown has a selected value or not. The problem is that selectedIndex, :selected, val(), etc. do return results for the following case:

<select>
<option value="123">123</option>
<option value="234">234</option>
</select>

Obviously the browser will display this dropdown with the 123 option being selected but it will be selected only because there are no other options, in reality this dropdown doesn't have a selected value because there is no "selected" property. So basically I am trying to find how to tell apart the above dropdown from this one

<select>
<option selected value="123">123</option>
<option value="234">234</option>
</select>
A: 

Quick solution:

<select>
<option selected></option>
<option value="123">123</option>
<option value="234">234</option>
</select>

Then see if you have a .val()

Jason
While this will work, it's not a solution, it's a workaround :) Unfortunately I am dealing with an already existing application where there is no first empty element
Eugene
@Eugene - ohh boo! `$('select option').first().before("<option selected></option>");` ? haha.
Jason
A: 

As far as I can tell, there is no functional distinction between your two examples. Essentially, the browser automatically selects the first option.

See, for example, the result of

$('option:selected')

on your first example.

If you really want to prevent this happening, you have two options. The first is to introduce a new, empty element into the select, per Jason's answer. The other option is to deselect the automatically selected value:

$(document).load(function(){
    $('option:selected').attr('selected', false);
});

This clears the selection. Any result of $('select').val() that isn't an empty string will therefore be a change by the user.

lonesomeday
+1  A: 
var hasValue = ($('select option[selected]').length > 0);
John Strickler
This works, thanks!
Eugene
A: 

This should work:

if($('#mySelect').find('[defaultSelected]').size()>0){/*do your stuff*/}
code90