Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select option without value using jQuery

Line of code in question:

$(this).find('select option:first').val();

If my select has this structure:

<select>
    <option> -- choose -- </option>
    <option value="some_value"> Some text</option>
</select>

the jQuery code I posted above will return --choose-- as a value. Is there a way I could understand if the option has a value or not, instead of returning the text in it?

like image 394
Ivanka Todorova Avatar asked Feb 13 '26 15:02

Ivanka Todorova


2 Answers

In your case, if your first option have no value attribute, you can use this:

$(this).find('select option[value]:first').val()

This returns the first option tag from your select but requiring that it haves the value attribute.

UPDATE:

Based on @Samuel Caillerie's comment, you can use multiple attribute selectors to avoid IE bizarre behaviours:

select option[value][value!=""]:first

That worked on Chrome and IE 10 with compatibility mode set to IE 8.

like image 190
DontVoteMeDown Avatar answered Feb 17 '26 09:02

DontVoteMeDown


$(this).find('select option:first').attr('value');

NOTE: this will return undefined if the value attribute is not set

like image 37
Spokey Avatar answered Feb 17 '26 09:02

Spokey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!