Radio button selected?

后端 未结 4 1965
别那么骄傲
别那么骄傲 2020-12-31 17:17

I\'d like to know for a specific radio button group if a radio button is selected or not with jQuery.

Thanks

相关标签:
4条回答
  • 2020-12-31 17:23
    <script type="text/javascript">
    ($('input[name=groupName]').is(':checked')) ? 
        $('input[name=groupName]:checked', '#myForm').val() :
            null;
    </script>
    
    0 讨论(0)
  • 2020-12-31 17:39

    The other answers have covered finding if one radio out of a group is checked, however if you want to find if a particular button (not a button group) is checked:

    $('#myRadioButton').attr('checked')
    

    or

    $('#myRadioButton').is(':checked')
    
    0 讨论(0)
  • 2020-12-31 17:40

    I think what you are asking for "shouldn't be done" because the W3 states having no checked radio button in a group results in undefined behavior.

    If no radio button in a set sharing the same control name is initially "on", user agent behavior for choosing which control is initially "on" is undefined.

    Since user agent behavior differs, authors should ensure that in each set of radio buttons that one is initially "on".

    Still, if you want to find the checked radio button, use:

    var checkedRadioButtons = $(':radio:checked[name=XXX]');
    

    Then check if one is checked:

    if(!checkedRadioButtons.length) {
        alert('None checked!');
    }
    
    0 讨论(0)
  • 2020-12-31 17:46
    if( $('input[name=groupName]').is(':checked') ){
          //do something
    }
    

    or my original answer before Paulo woke me up

      if( $('input[name=groupName]:radio:checked').length ){
          //do something
      }
    
    0 讨论(0)
提交回复
热议问题