[jquery] How to check if an option is selected?

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

Apparently, the isChecked doesn't work. SO my question is what is the proper way to do this? Thanks.

This question is related to jquery select option

The answer is


You can get the selected option this way:

$('#mySelectBox option:selected')...

LIVE DEMO

But if you want to iterate all the options, do it with this.selected instead of this.isChecked which doesn't exist:

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

LIVE DEMO

Update:

You got plenty of answers suggesting you to use this:

$(this).is(':selected') well, it can be done a lot faster and easier with this.selected so why should you use it and not the native DOM element method?!

Read Know Your DOM Properties and Functions in the jQuery tag info


In my case I don't know why selected is always true. So the only way I was able to think up is:

var optionSelected = false;
$( '#select_element option' ).each( function( i, el ) {
    var optionHTMLStr = el.outerHTML;

    if ( optionHTMLStr.indexOf( 'selected' ) > 0 ) {
        optionSelected = true;
        return false;
    }
});

You can use this way by jquery :

_x000D_
_x000D_
$(document).ready(function(){_x000D_
 $('#panel_master_user_job').change(function () {_x000D_
 var job =  $('#panel_master_user_job').val();_x000D_
 alert(job);_x000D_
})_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<select name="job" id="panel_master_user_job" class="form-control">_x000D_
                                    <option value="master">Master</option>_x000D_
                                    <option value="user">User</option>_x000D_
                                    <option value="admin">Admin</option>_x000D_
                                    <option value="custom">Custom</option>_x000D_
                                </select>
_x000D_
_x000D_
_x000D_


Consider this as your select list:

<select onchange="var optionVal = $(this).find(':selected').val(); doSomething(optionVal)">

                                <option value="mostSeen">Most Seen</option>
                                <option value="newst">Newest</option>
                                <option value="mostSell">Most Sell</option>
                                <option value="mostCheap">Most Cheap</option>
                                <option value="mostExpensive">Most Expensive</option>

                            </select>

then you check selected option like this:

function doSomething(param) {

    if ($(param.selected)) {
        alert(param + ' is selected!');
    }

}

If you only want to check if an option is selected, then you do not need to iterate through all options. Just do

if($('#mySelectBox').val()){
    // do something
} else {
    // do something else
}

Note: If you have an option with value=0 that you want to be selectable, you need to change the if-condition to $('#mySelectBox').val() != null


use

 $("#mySelectBox option:selected");

to test if its a particular option myoption:

 if($("#mySelectBox option:selected").text() == myoption){
          //...
 }

If you want to check selected option through javascript

Simplest method is add onchange attribute in that tag and define a function in js file see example if your html file has options something like this

 <select onchange="subjects(this.value)">
               <option>Select subject</option>
               <option value="Computer science">Computer science</option>
               <option value="Information Technolgy">Information Technolgy</option>
               <option value="Electronic Engineering">Electronic Engineering</option>
               <option value="Electrical Engineering">Electrical Engineering</option>
 </select>

And now add function in js file

function subjects(str){
    console.log(`selected option is ${str}`);
}

If you want to check selected option in php file

Simply give name attribute in your tag and access it php file global variables /array ($_GET or $_POST) see example if your html file is something like this

<form action="validation.php" method="POST">
             Subject:<br>
            <select name="subject">
               <option>Select subject</option>
               <option value="Computer science">Computer science</option>
               <option value="Information Technolgy">Information Technolgy</option>
               <option value="Electronic Engineering">Electronic Engineering</option>
               <option value="Electrical Engineering">Electrical Engineering</option>
            </select><br>

         </form>

And in your php file validation.php you can access like this

$subject = $_POST['subject'];
echo "selected option is $subject";

If you need to check option selected state for specific value:

$('#selectorId option[value=YOUR_VALUE]:selected')

If you're not familiar or comfortable with is(), you could just check the value of prop("selected").

As seen here:

$('#mySelectBox option').each(function() {
    if ($(this).prop("selected") == true) {
       // do something
    } else {
       // do something
    }
});?

Edit:

As @gdoron pointed out in the comments, the faster and most appropriate way to access the selected property of an option is via the DOM selector. Here is the fiddle update displaying this action.

if (this.selected == true) {

appears to work just as well! Thanks gdoron.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to select

Warning: Use the 'defaultValue' or 'value' props on <select> instead of setting 'selected' on <option> SQL query to check if a name begins and ends with a vowel Angular2 *ngFor in select list, set active based on string from object SQL: Two select statements in one query How to get selected value of a dropdown menu in ReactJS DATEDIFF function in Oracle How to filter an array of objects based on values in an inner array with jq? Select unique values with 'select' function in 'dplyr' library how to set select element as readonly ('disabled' doesnt pass select value on server) Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Examples related to option

Get Selected value from dropdown using JavaScript html select option SELECTED How to check if an option is selected? JQuery refresh select box android: changing option menu items programmatically How to implement the --verbose or -v option into a script? set option "selected" attribute from dynamic created option How to preSelect an html dropdown list with php? jQuery remove selected option from this using href links inside <option> tag