需要提醒 jquery 中未选中的单选按钮

Need to alert for unchecked radio buttons in jquery

例子

  <div id="radio">
<input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" value="2"  /><label for="radio2">Choice 2</label>
<input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Choice 3</label>

 <div id="radio">
<input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" value="2" checked="checked" /><label for="radio2">Choice 2</label>
<input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Choice 3</label>

  <div id="radio">
<input type="radio" id="radio1" name="radio" value="1" /><label for="radio1">Choice 1</label>
<input type="radio" id="radio2" name="radio" value="2" checked="checked" /><label for="radio2">Choice 2</label>
<input type="radio" id="radio3" name="radio" value="3" /><label for="radio3">Choice 3</label>

以上单选组是动态生成的。 我需要在其中识别未选中的无线电组。

首先,当您希望用户一次只能选择一个时,可以使用单选按钮。所以,我认为您更愿意使用复选框,而不是单选按钮。

话虽如此,我认为使用 jQuery 实现目标的最简单方法是使用 :not 选择器。此代码将为您提供所有未选中的复选框:

var notChecked = $('input:not(:checked)')

这是一个 fiddle 演示:http://jsfiddle.net/nasuf96b/

显然必须进行一些错误处理,但您明白了。

祝你好运。

编辑

我现在明白你在追求什么了。看看这个 fiddle:http://jsfiddle.net/nasuf96b/1/。 它会告诉您是否没有选择组中的任何内容,我认为这就是您想要做的。

$('input').on('click', function() {
    check_all();   
});

function check_all() {
    var outputText = 'These are not checked: ';
    var myDivs = $('div.radio');
    for (var i=0; i<myDivs.length; i++) {
        var isChecked = false;
        var childInputs = myDivs[i].getElementsByTagName('input');
        for (var j=0; j<childInputs.length; j++) {
            if (childInputs[j].checked == true) {
                isChecked = true;
            }
        }
        if (isChecked == false) {
            outputText += (i+1) +', ';   
        }
    }
    alert(outputText.slice(0, -2));
}