如何循环浏览单选按钮列表

| 我在线搜索,但找不到在.net中选择单选按钮列表控件的好方法 因此,我向每个单选按钮列表中添加了一个类,并使用类选择器循环了每个类,但是似乎每当一个更改时,所有更改都会改变。看我的代码如下: 这是jQuery部分:
function Checkform() {
    result=true;
    $(\'.rbl\').each(function() {
            var cc = $(this + \"[checked]\").val();
            if (cc == undefined) {
                result = false;
                return false;
            }
        });
        return result;
    }
这是网络部分:
<form id=\"form1\" runat=\"server\" onsubmit=\"return Checkform();\">
<asp:RadioButtonList ID=\"RadioButtonList1\" class=\"rbl\"  runat=\"server\">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>
        <asp:ListItem>3</asp:ListItem>
    </asp:RadioButtonList>

    <asp:RadioButtonList ID=\"RadioButtonList2\" class=\"rbl\" runat=\"server\" 
        RepeatDirection=\"Horizontal\">
        <asp:ListItem>1</asp:ListItem>
        <asp:ListItem>2</asp:ListItem>
        <asp:ListItem>3</asp:ListItem>
        <asp:ListItem>4</asp:ListItem>
    </asp:RadioButtonList>
我想做的是在提交表单之前检查所有单选按钮列表控件是否具有其选定的值。但这就像一个选择了值一样,无论天气如何,该函数都会返回true。请帮我解决这个问题。先感谢您。     
已邀请:
这个怎么样:
function Checkform() {
    var result = true;
    $(\'.rbl\').each(function() {
        var checked = $(this).find(\'input:radio:checked\');
        if (checked.length == 0) {
            result = false;
            return;
        }
    });
    return result;
}
这将检查每个组,并确定在该组中是否选择了放射线。键是
$(this).find(\'..\')
,它返回当前组中的所有“选中”单选按钮;如果未选择,则为零;如果选择了一个,则为1。     
是的,您的函数将返回true,因为它首先假设其条件为“ true”。当它遍历\“ RadioButtonList1 \”并找到一个选定的控件时(我假设默认情况下将是一个控件),它还将返回true。 尝试以下代码:
var checkedRadioButtons = $(\'#form1 .rbl input:checked\');
该行将仅返回其值设置为选中的那些单选按钮。然后,您可以遍历这些元素以获得更多信息,例如它们的值:
checkedRadioButtons.each(function(Index){
   return $(this).val();
});
    
如果我正确理解了您的问题,则要确保在提交之前,每个
RadioButtonList
都已选中。有两种方法可以实现此目的。 看起来您正在使用WebForms,因此您无需触摸jQuery,可以使用RequiredFieldValidator(每个
RadioButtonList
一个)来完成此操作,并且一切就绪。 如果您想使用jQuery方式,那么将您的问题考虑为\“是否选择了任何RadioButtonLists都没有。\”要回答它,您可以: 选择具有适当类别的所有单选按钮 获取一个独特的名称列表(这就是单选按钮的分组方式)。有很多方法可以做到这一点,有些方法比其他方法容易。您可以使用map实用程序创建名称列表(然后可以将其区分)
var all = $.map( 
    $(\".rbl input:radio\"),
    function(n, i){ return n.attr(\"name\") }
);
选择具有适当类别的所有
checked
单选按钮(这是一个单选按钮列表,一次不能有多个
checked
元素,因此它们将是唯一的)
var selected = $(\".rbl input:radio:checked\")
比较列表以查看它们是否大小相同。如果是,则每个列表都选择了一个项目;如果不是,则至少一个列表没有选择任何项目。您也可以使用map实用程序将其转换为名称列表,但这不是必需的,因为您只是在比较数组长度。 如果您还想知道哪个单选按钮列表没有选定的值,则需要在步骤3的数组上应用map实用程序,然后查看哪些名称在
all
中而不在
selected
中。     
这将验证每个RadioButtonList都有一个选中的项目。因此,如果有2个列表和2个选中项,则返回true。
function Checkform() {
    return $(\".rbl :checked\").length == $(\".rbl:has(:radio)\").length
}
    

要回复问题请先登录注册