0

我正在尝试一个由 RadioButtonList 组成的简单验证rblstPallet。我尝试了以下代码:

javascript

var rblstPallet = document.getElementById('rblstPallet');
var counter = 0;
for (var intCount = 0; intCount < rblstPallet.length; intCount++) {
    if (rblstPallet[intCount].checked) {  //this step is not working
        console.log(intCount); //I checked using this step
        counter++;
    }
}
if (counter == 0) {        
    //MSG: please select any item
}
else {
    // Redirect to next page function
}

.aspx

<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal">
     <asp:ListItem>Wood</asp:ListItem>
     <asp:ListItem>Plastic</asp:ListItem>
     <asp:ListItem>None</asp:ListItem>
</asp:RadioButtonList>

问题是,如果我什至选择了一个单选按钮,那么该counter值也保持不变。当我调试代码时,我知道那行

if (rblstPallet[intCount].checked) {

甚至没有执行,甚至没有在控制台中显示任何错误。我正在通过这个链接。我试过这个链接(不工作)。

请帮忙。

4

3 回答 3

2

RadioButtonList 被转换为具有类似于 radiobuttonlist id 的 id 的单选按钮,您需要iterate通过 DOM 来查找matching元素。

function getRadioButtonListSelections(radioButtonListName)
{
     int selectionCount = 0;
     for(i=0;i<document.forms[0].length;i++)
     {
            e=document.forms[0].elements[i];
            if (e.id.indexOf(radioButtonListName) != -1 && e.checked)
                selectionCount++;
     }  
     return selectionCount; 
}       

alert(getRadioButtonListSelections('rblstPallet'));
于 2012-12-17T10:06:21.997 回答
0

代替

var rblstPallet = document.getElementById('rblstPallet');

经过

var rblstPallet = document.getElementById('<%= rblstPallet.ClientID %>');

如果您想验证您的单选按钮列表,为什么不使用验证器控件?

<asp:RequiredFieldValidator ID="rfvPallet" runat="server"
      ControlToValidate="rblstPallet" ErrorMessage="RequiredFieldValidator">
 </asp:RequiredFieldValidator>
于 2012-12-17T09:53:18.177 回答
0

要么使用:

var rblstPallet = document.getElementById('<%=rblstPallet.ClientID=>');

或者

将客户端 ID 模式设置为静态:

<asp:RadioButtonList ID="rblstPallet" runat="server" RepeatDirection="Horizontal" ClientIDMode="static">

并找到并循环遍历每个单选按钮:

var rblstPallet = document.getElementById('rblstPallet');
rblstPallet  = rblstPallet.querySelectorAll('input[type="radio"]')
于 2012-12-17T09:51:50.443 回答