Search code examples
jqueryhtml-select

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.


Solution

  • 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