Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery : How to check if NO option was explicitly selected in a select box

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?

like image 898
craftsman Avatar asked Mar 21 '12 07:03

craftsman


People also ask

How can check select option selected or not in jQuery?

Use the jQuery: selected selector in combination with val () method to find the selected option value in a drop-down list.

How check value exists or not in jQuery?

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

What does .select to jQuery?

The select() method triggers the select event, or attaches a function to run when a select event occurs.

How do you check if something is selected in JavaScript?

First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.


1 Answers

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.

like image 115
nickalchemist Avatar answered Oct 15 '22 10:10

nickalchemist