Adam Boostani
Adam Boostani

Reputation: 6247

How to detect the default dropdown option vs. selected with js/jquery?

I want to show the value of a dropdown only if it has actually a selected option with selected attribute. Browsers are detecting the first dropdown option by default regardless if it has selected attr or not. So :selected method gives you a result regardless. Is there any way to detect if the selected option actually has the selected attribute?

Upvotes: 1

Views: 155

Answers (2)

Andrew Roth
Andrew Roth

Reputation: 1073

In your option tags, you can have a property of "selected"

<select>
    <option value="">Please select an option</option>
    <option selected value="foobar">foobar</option>
</select>

For jQuery you can do this:

$("select option").each(function(){
    if($(this).prop("selected") == true)
    {
        alert("found the selected option. The value is: " + $(this).val());
    }
});

Fiddle: http://jsfiddle.net/o24g9feo/

Upvotes: 1

2147483647
2147483647

Reputation: 95

$( "#optionTagID" ).val(); jQuery docs Gives you the value of the selected option. You can check if this is the desired value and then hide the element accordingly.

Upvotes: 1

Related Questions