使用JavaScript在asp.net中验证radiobuttonlist [英] validation of radiobuttonlist in asp.net using javascript
问题描述
我必须使用JavaScript验证单选按钮.如果未选择任何选项,它应该显示一条消息.
i have to validate a radio button using javascript. it should show a message if none of the option is selected.
我的单选按钮代码是:
<asp:RadioButtonList ID="welldata" runat="server" RepeatDirection="Horizontal" Width="100px">
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:RadioButtonList>
,提交按钮为:
<asp:Button ID="next2" runat="server" Text=">>" Width="46px"
OnClientClick="return next2()"/>
相应的javascript函数是:
the corresponding javascript function is :
function next2() {
var listItemArray = document.getElementById('<%=welldata.ClientID %>');
var isItemChecked = false;
var length1 = listItemArray.length;
for (var i=0; i<length1; i++)
{
var listItem = listItemArray[i];
document.write(listItem);
if ( listItem.checked )
{
alert(listItem.value);
isItemChecked = true;
}
}
if ( isItemChecked == false )
{
alert('Nothing is checked for welldata!');
return false;
}
return true;
}
在调试时,我注意到thaat函数已执行,但没有进入for循环.我也尝试过
while debugging i noticed thaat function is executed but doesn't enter the for loop. also i tried
document.write(isItemChecked);
document.write(listItemArray);
document.write(length1);
,输出为:
错误的[object HTMLTableElement]未定义
false [object HTMLTableElement] undefined
推荐答案
wellData
RadioButtonList
ASP.NET服务器控件将在浏览器中呈现为带有数字的表下方的 input type ="radio"
控件,每个控件都具有相同的 name
.
The wellData
RadioButtonList
ASP.NET server control will render in the browser as a table with a number of input type="radio"
controls under it, each with the same name
.
因此,您需要先在 table
标记内获取 input
标记:
So, you need to get the input
tags inside the table
tag first:
var wellData = document.getElementById('<%=welldata.ClientID %>');
var listItemArray = wellData.getElementsByTagName('input');
当然,如果您出于某些奇怪的原因手动执行此操作,则为
.您可以使用 RequiredFieldValidator
控件自动完成此操作.
This is, of course, if you are doing this manually for some odd reason. You can do it automatically with a RequiredFieldValidator
control.
<asp:RadioButtonList ID="welldata" runat="server" RepeatDirection="Horizontal" Width="100px">
<asp:ListItem></asp:ListItem>
<asp:ListItem></asp:ListItem>
</asp:RadioButtonList>
<asp:RequiredFieldValidator ID="rfvWellData" runat="server" ControlToValidate="wellData" Display="Dynamic" ErrorMessage="Pick yourself some well data" />
这篇关于使用JavaScript在asp.net中验证radiobuttonlist的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!