jQuery: How to check if the NO option has been explicitly selected in a selection box

advertisements

Is it possible to detect if no option was explicitly selected in a select box?

I have tried these methods but none of them works:

<select id="mySelect">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select>

Trial 1:

alert($('#select option:selected').length); // returns 1

Trial 2:

alert($('#select option[selected=selected]').length); // returns 1

Trial 3:

alert($('#select option:selected').attr('selected')); // returns 'selected'

Any ideas SO people?


Try This:

<select id="mySelect">
  <option value="1">First</option>
  <option value="2">Second</option>
  <option value="3">Third</option>
  <option value="4">Fourth</option>
</select><input type="button" id="btncheck" value="check"/>

Use this JS:

$('#btncheck').click(function(){
     if ($("#mySelect ")[0].selectedIndex <= 0) {
                alert("Not selected");
            }
    else
        alert("Selected");
});

​It will check if your dropdown was selected.

Try this fiddle: http://jsfiddle.net/aPYyt/

​Hope it helps!

PS: You will have to make first value as default value.