How to check if an option is selected?

0x56794E picture 0x56794E · Apr 18, 2012 · Viewed 364k times · Source
$('#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.

Answer

iambriansreed picture iambriansreed · Apr 18, 2012

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