JS/Jquery: how to check whether dropdown has selec

2020-08-09 09:56发布

问题:

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>

回答1:

var hasValue = ($('select > [selected]').length > 0);

Alternatively,

var hasValue = $('select').has('[selected]');


回答2:

Quick solution:

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

Then see if you have a .val()



回答3:

The approved answer doesn't seem to work for me.

Here is how I do it to check if all select options are selected:

if($('select option:selected').length > 0) {
/* Do your stuff here */
}


回答4:

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.



回答5:

This should work:

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