jQuery and radio button groups

后端 未结 3 1894
南旧
南旧 2020-12-06 00:56

In jQuery, I\'d like to select all groups of radio buttons where there are no buttons checked.

Or, is there a way in which I can select all radio button groups and i

相关标签:
3条回答
  • 2020-12-06 01:06

    To select all radio by group name and obtain only the list of different names:

        function selectRadioByGroupName() {
            return $.unique($('input:radio').map(function(index, element) {
                return this.name;
            }));
        }
    

    An example snippet:

    function selectRadioByGroupName() {
      return $.unique($('input:radio').map(function(index, element) {
        return this.name;
      }));
    }
    
    
    
    $(function () {
      selectRadioByGroupName().each(function(index, element) {
        $('body').append($('<p>First Group name is: ' + element + '</p>'));
      });
    });
    <script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
    
    <form action="">
        <p>
            Q1:
        </p>
        <input type="radio" name="gender" value="male"> Male<br>
        <input type="radio" name="gender" value="female"> Female<br>
        <input type="radio" name="gender" value="other"> Other
        <br />
        <p>
            Q2:
        </p>
        <input type="radio" name="status" value="male"> Single<br>
        <input type="radio" name="status" value="female"> Married<br>
        <input type="radio" name="status" value="other"> Other
        <br />
        <input type="button" name="submit_id" value="Submit" onclick="submitAnswers()">
    </form>

    After getting the different group names it's possible to cycle on them.

    0 讨论(0)
  • 2020-12-06 01:26

    To find all radio groups:

    var radio_groups = {}
    $(":radio").each(function(){
        radio_groups[this.name] = true;
    })
    

    to find which radio group has checked radio boxes and which hasn't:

    for(group in radio_groups){
        if_checked = !!$(":radio[name='"+group+"']:checked").length
        alert(group+(if_checked?' has checked radios':' does not have checked radios'))
    }
    
    0 讨论(0)
  • 2020-12-06 01:26

    Support for multiple groups and pre-checked.

    $('input').click(function() {
        var $t = $(event.target);
        if ($t.hasClass('checked')) $t.removeAttr('checked');
        else $('input[type="radio"][name="' + $t.prop('name') + '"]').not($t).removeClass('checked');
        $t.toggleClass('checked');
    }).filter(':checked').addClass('checked');​
    

    ```

    Proof: http://jsfiddle.net/abrkn/PGW2Z/

    0 讨论(0)
提交回复
热议问题