Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS/Jquery: how to check whether dropdown has selected values?

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>
like image 895
Eugene Avatar asked Oct 25 '10 20:10

Eugene


People also ask

How do you check if a dropdown is selected in jQuery?

$('#mySelectBox option'). each(function() { if ($(this). isChecked()) alert('this option is selected'); else alert('this is not'); });

How do you check if dropdown is selected or not?

Use the tagName property to check if an element is a select dropdown, e.g. if (select. tagName === 'SELECT') {} .

How can I check whether a option already exist in select by jQuery?

var exists = $("#yourSelect option") . filter(function (i, o) { return o. value === yourValue; }) .

How check dropdown is empty or not in jQuery?

The Best Answer isval() === "") { // ... }


1 Answers

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

Alternatively,

var hasValue = $('select').has('[selected]');
like image 137
John Strickler Avatar answered Oct 11 '22 13:10

John Strickler