How to check if an option is selected?

JqueryHtml Select

Jquery Problem Overview


$('#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.

Jquery Solutions


Solution 1 - Jquery

UPDATE

A more direct jQuery method to the option selected would be:

var selected_option = $('#mySelectBox option:selected');

Answering the question .is(':selected') is what you are looking for:

$('#mySelectBox option').each(function() {
    if($(this).is(':selected')) ...

The non jQuery (arguably best practice) way to do it would be:

$('#mySelectBox option').each(function() {
    if(this.selected) ...

Although, if you are just looking for the selected value try:

$('#mySelectBox').val()

If you are looking for the selected value's text do:

$('#mySelectBox option').filter(':selected').text();

Check out: http://api.jquery.com/selected-selector/

Next time look for duplicate SO questions:

https://stackoverflow.com/questions/8809265/get-current-selected-option or https://stackoverflow.com/questions/10102252/set-selected-option or https://stackoverflow.com/questions/10011802/how-to-get-this-selected-option-in-jquery or https://stackoverflow.com/questions/8974250/optionselected-true-doesnt-work

Solution 2 - Jquery

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

Solution 3 - Jquery

You can use this way by jquery :

$(document).ready(function(){
 $('#panel_master_user_job').change(function () {
 var job =  $('#panel_master_user_job').val();
 alert(job);
})
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="job" id="panel_master_user_job" class="form-control">
                                    <option value="master">Master</option>
                                    <option value="user">User</option>
                                    <option value="admin">Admin</option>
                                    <option value="custom">Custom</option>
                                </select>

Solution 4 - Jquery

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.

Solution 5 - Jquery

use

 $("#mySelectBox option:selected");

to test if its a particular option myoption:

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

Solution 6 - Jquery

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!');
    }

}

Solution 7 - Jquery

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

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

Solution 8 - Jquery

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;
    }
});

Solution 9 - Jquery

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

Solution 10 - Jquery

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";

Solution 11 - Jquery

var selectedOption = $("option:selected", #selectIdentifier)

<select id="selectIdentifier">
<option>1</option>
<option>2</option>
<option selected="selected">3</option>
</select>

EDIT: This answer is valid and avoids the religious wars of jQuery or not. The key in this answer is :selected. To answer the actual question the OP needs to have created some differentiation between options to be able to query weather a specific option is selected. eg id, data-, value etc. decoration on the options themselves.

Solution 12 - Jquery

You can also do a double attribute selector in CSS

$('[value="your_value"][selected="selected"]')

So to fire when "your_value" is selected:

if( $('[value="your_value"][selected="selected"]') ) {
  // do something
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Question0x56794EView Question on Stackoverflow
Solution 1 - JqueryiambriansreedView Answer on Stackoverflow
Solution 2 - Jquerygdoron is supporting MonicaView Answer on Stackoverflow
Solution 3 - JqueryAmirView Answer on Stackoverflow
Solution 4 - JqueryveeTrainView Answer on Stackoverflow
Solution 5 - JqueryMouna CheikhnaView Answer on Stackoverflow
Solution 6 - JqueryMasoud DarvishianView Answer on Stackoverflow
Solution 7 - JquerydimpiaxView Answer on Stackoverflow
Solution 8 - JquerySergey OnishchenkoView Answer on Stackoverflow
Solution 9 - JqueryAdamView Answer on Stackoverflow
Solution 10 - JqueryAbhishek Pratap SinghView Answer on Stackoverflow
Solution 11 - JqueryIshit VyasView Answer on Stackoverflow
Solution 12 - JqueryPeter Højlund PalluthView Answer on Stackoverflow