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

General Grievance
  • 4,555
  • 31
  • 31
  • 45
0x56794E
  • 20,883
  • 13
  • 42
  • 58
  • 2
    00zebra00, thanks for finding an answer among the many options below. However, please be sure to make notice of the conversation in the comments below about 'the best' way for accessing the selected property. The general gist is that when you can access an element directly in javascript (using `this.selected`) that you should bypass using jQuery (`$(this).prop("selected")`) but they _will_ both work for you. – veeTrain Apr 19 '12 at 11:40
  • Possible duplicate of [jQuery Get Selected Option From Dropdown](https://stackoverflow.com/questions/10659097/jquery-get-selected-option-from-dropdown) – Iman Kermani Mar 03 '18 at 13:07

15 Answers15

306

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:

Get current selected option or Set selected option or How to get $(this) selected option in jQuery? or option[selected=true] doesn't work

Community
  • 1
  • 1
iambriansreed
  • 21,935
  • 6
  • 63
  • 79
  • It uses jQuery for no good reason. use the native js DOM properties. take a look on [this](http://stackoverflow.com/a/10213695/601179) – gdoron Apr 18 '12 at 16:29
  • 3
    It looks like you didn't read my answer. `this.selected` can be used instead of `$(this).is(":selected")` I guess there is no need for a jsperf for this, right? I have nothing against using jQuery!, but use it when you need it, not when it give nothing but overhead and more code. – gdoron Apr 18 '12 at 16:31
  • @gdoron `this.selected` is completely valid but he asked for the proper jQuery way to do it. – iambriansreed Apr 18 '12 at 16:34
  • People keep thinking that jQuery isn't javascript, well... it's an abstraction library above javascript, **it definitely shouldn't replace javascript!** – gdoron Apr 18 '12 at 16:36
  • 2
    @gdoron **I totally agree with you.** Maybe those of us brought up on jQuery need to take a remedial JavaScript class. :) – iambriansreed Apr 18 '12 at 16:38
  • It looks like you downvoted all the "competing answers", I hope I'm wrong. – gdoron Apr 18 '12 at 16:43
  • 2
    @gmoron No, my question was down voted and up voted. Good detective work though. – iambriansreed Apr 18 '12 at 16:44
27

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

Community
  • 1
  • 1
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • 1
    @downvoter, care to comment? get out of the shades and fight! :) – gdoron Apr 18 '12 at 16:37
  • Maybe because you didn't answer the question but gave best practice. ;) – iambriansreed Apr 18 '12 at 16:39
  • 1
    @iambriansreed. Ha?! I didn't answer the question? **what part in the question remained unanswered?** – gdoron Apr 18 '12 at 16:41
  • 2
    Interesting discussions here. :) Not sure why all the DVs, but I UV'd everyone who used `this.selected`. I agree with your comments about jQuery overuse/abuse. Part of knowing jQuery, is knowing when to *not* use it. That said, keep in mind that the `':selected'` selector is a custom Sizzle selector, so using it disables the use of `querySelectorAll` in supported browsers. It's certainly not the end of the world, since it provides some nice, short code, but I personally tend to avoid the Sizzle-only stuff. –  Apr 19 '12 at 13:59
  • @gdoron As you pointed this question in Meta, I got interested. Regarding DV, [this node](http://stackoverflow.com/a/10572407/1249581) may be useful to you. – VisioN Jun 03 '12 at 00:38
  • @VisioN. Add [this thread](http://stackoverflow.com/q/10196264/601179) to the list. stack exchange script is awful, but I hate meta, I'll never suggest something there again. (I got an algorithm to catch **every** serial votes(up+down), But hell! I'm not visiting this site again!) – gdoron Jun 03 '12 at 08:23
  • @gdoron Yeah, I read your last comment on Meta. For me all written in your question makes sense but I agree with amnotiam, you should just use SO as solution archive, giving small contribution back (not like guys as thecodeparadox `:)`). There are a lot of people who can make SO better, let them do it. Saved nerves should be much important for you. Come on, friend ;) – VisioN Jun 03 '12 at 08:32
  • @BoltClock. This thread is full of downvotes, I was pointed by vision to other mystircal downvotes where iambriansreed participated, And found another thread after 10 seconds of search. I think a mod needs to check it out. Honestly, I don't care too much, but those kind of things ruins stackoverflow. one of the users left the site after the downvote he got(from seeing he profile). [This search at google can help you find out what is going on: "iambriansreed downvote site:stackoverflow.com" – gdoron Jun 03 '12 at 13:07
8

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>
Amir
  • 310
  • 3
  • 10
5

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.

veeTrain
  • 2,915
  • 2
  • 26
  • 43
  • Can you please explain me why should he use `$(this).prop("selected")` instead of `this.selected` ?! what does it give you??! p.s. I'm not the downvoter... – gdoron Apr 18 '12 at 16:38
  • @gdoron, the main advantage that I thought of was familiarity. I'm not sure what `is` is best used for but I like accessing my properties by prop and attr. In most scenarios it may well be just a matter of taste. Yes, there is a curious rash of down-voting! – veeTrain Apr 18 '12 at 16:51
  • 2
    I suggest to read the **Know Your DOM Properties and Functions** part of the `jQuery` [tag info](http://stackoverflow.com/tags/jquery/info). there is no reason to use slower code + more code to do simple thing. `.is()` should be used for complicated selector like `$(...).is('.foo > [name="aaa"] input') or for properties that are not native DOM elements properties like `$(...).is(":visiable"). – gdoron Apr 18 '12 at 16:56
  • @gdoron; thanks so much for pointing that out. I have updated my answer accordingly. – veeTrain Apr 18 '12 at 17:04
  • No prob. You can upvote my answer if you think it's better then the others. (I don't want the answer with `$(this).is(':selected')` to be accepted. Stackoverflow should be used to learn best practices, not common mistakes...) – gdoron Apr 18 '12 at 17:26
  • @gdoron; sounds good to me. Done. If you feel my answer is useful you could as well. – veeTrain Apr 18 '12 at 17:30
  • Guess what... he accepted that answer... I don't feel comfortable leaving the OP a comment about his selection, can you do it? – gdoron Apr 19 '12 at 07:35
2

use

 $("#mySelectBox option:selected");

to test if its a particular option myoption:

 if($("#mySelectBox option:selected").text() == myoption){
          //...
 }
Mouna Cheikhna
  • 38,870
  • 10
  • 48
  • 69
2

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

}
Masoud Darvishian
  • 3,754
  • 4
  • 33
  • 41
1

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

$('#selectorId option[value=YOUR_VALUE]:selected')
dimpiax
  • 12,093
  • 5
  • 62
  • 45
1
$("#mySelectBox").attr("checked")
  ? alert("this option is selected")
  : alert("this is not");
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Oct 28 '22 at 19:20
0

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;
    }
});
Sergey Onishchenko
  • 6,943
  • 4
  • 44
  • 51
0

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

Adam
  • 25,960
  • 22
  • 158
  • 247
0

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";
Abhishek Pratap Singh
  • 613
  • 3
  • 11
  • 18
0
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.

Joe Johnston
  • 2,794
  • 2
  • 31
  • 54
Ishit Vyas
  • 33
  • 8
0

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
}
0

You can check if selected or not with value

var selected_option = $('#propertyArea option:selected').val();
        if(selected_option){
            console.log('selected ...');
            console.log(selected_option);
        }else{
            console.log('not selected');
        }
Mandeep Singh
  • 455
  • 2
  • 14
-2

$(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>
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
  • Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P Aug 10 '23 at 21:30