如何从单选按钮列表中查找jQuery中的已检查单选按钮

时间:2012-09-26 14:53:52

标签: jquery

在下面的示例中,我希望选择“radios”列表中的所有“:checked”单选按钮。怎么样?

var radios = someDiv.find("input[type=radio]");
if (radios.length > 0)
{
    // I wish to find all the checked radio buttons in the
    // "radios" list - this doesn't work:
    var checkedRadios = radios.find(":checked");

    if (checkedRadios.length == 0)
        alert("You have to select an option stoopid");
}

3 个答案:

答案 0 :(得分:1)

要使代码按原样运行,只需将find替换为filter

var checkedRadios = radios.filter(":checked");

除非您有任何特定的理由进行两步选择,否则我建议您选择带有一个选择器的单选按钮

var checkedRadios = someDiv.find("input[type=radio]:checked");

答案 1 :(得分:1)

试试这个

if(someDiv.find("input[type=radio]:checked").length == 0)
  alert("You have to select an option stoopid");

如果你知道div id

if($('#someDivId').find("input[type=radio]:checked").length == 0)
      alert("You have to select an option stoopid");

如果您知道div类,但它将对所有具有此类的div进行操作

 if($('.someDivClass').find("input[type=radio]:checked").length == 0)
          alert("You have to select an option stoopid");

答案 2 :(得分:0)

var radios = someDiv.find("input[type=radio]:checked");应该有效


<强>更新

var radios = someDiv.find("input[type=radio]");

// radios are there
if (radios.length > 0)
{
    var numChecked = 0;
    radios.each(function() {
        if($(this).is(':checked')) numChecked++;
    });

    if (numChecked == 0) 
        alert("You have to select an option stoopid");
}