jQuery和单选按钮组

17
在jQuery中,我希望选择所有未选中任何按钮的单选按钮组。

或者,是否有一种方法可以选择所有单选按钮组并迭代这些组?

我正在动态向页面添加N个单选按钮组,并且在事先不知道单选按钮组名称的情况下进行操作。

3个回答

37
为了找到所有单选按钮组:

To find all radio groups:

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

查找哪个单选按钮组中有选中的单选框,哪个没有选中:

for(group in radio_groups){
    if_checked = !!$(":radio[name='"+group+"']:checked").length
    alert(group+(if_checked?' has checked radios':' does not have checked radios'))
}

2
!!代表什么?为什么要使用它? - Sven Larson
双重否定是将布尔值连续两次转换,因此 !!true = true - Davor Lucic
我知道这已经过时了,但是它对我帮助很大!我只想要一种简单的方法来确保每个单选按钮组都被选中,而这就是它。 - LittleTreeX

0

通过组名选择所有单选框并仅获取不同名称的列表:

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

一个代码片段的例子:

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>

获取不同的组名后,可以对它们进行循环。

0

支持多个组和预选。

$('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');​

```

证明:http://jsfiddle.net/abrkn/PGW2Z/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接