我必须使用javascript验证单选按钮。如果没有选择任何选项,则应该显示一条消息。
我的单选按钮代码是:
<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函数是:
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循环。我也试过
document.write(isItemChecked);
document.write(listItemArray);
document.write(length1);产出如下:
假对象HTMLTableElement未定义
发布于 2014-06-22 09:11:44
wellData RadioButtonList ASP.NET服务器控件将在浏览器中呈现为一个表,其中包含许多input type="radio"控件,每个控件都具有相同的name。
因此,您需要首先在input标记中获取table标记:
var wellData = document.getElementById('<%=welldata.ClientID %>');
var listItemArray = wellData.getElementsByTagName('input');当然,如果您是出于一些奇怪的原因手动执行此操作的,那么这就是。您可以使用RequiredFieldValidator控件自动完成此操作。
<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" />发布于 2014-06-22 09:09:24
您使用的是一个RadiobuttonList,它按默认情况呈现为表。如果您通过id document.getElementById('<%=welldata.ClientID %>')选择dom元素,那么您选择的是表而不是RadioButtonList。如果您想选择单选按钮,那么必须遍历childNodes of listItemArray才能获得单选按钮。或者,您可以使用jquery来选择单选按钮,因为它们的id将以单选按钮列表的id开始(它们看起来类似于welldata_0或welldata_1)。
这行jquery代码将获得单选按钮。
var listItemArray = $("input[id^='welldata']")发布于 2014-06-22 09:01:39
试试这个:
function next2() {
if(document.getElementById('<%=welldata.ClientID %>').checked==false)
{
alert('Nothing is checked for welldata!');
return false;
}
return true;
}
or 使用RequiredFieldValidator
<asp:RequiredFieldValidator
ID="ReqiredFieldValidator1"
runat="server"
ControlToValidate="welldata"
ErrorMessage="Select your welldata!"
> 检查下面的链接
http://asp-net-example.blogspot.in/2009/02/aspnet-requiredfieldvalidator-example.html
http://www.itechies.net/tutorials/jscript/jsexample.php-pid-jform.htm#rb
http://www.codeproject.com/Questions/499602/RequiredplusFieldplusValidatorplusForplusRadioplus
https://stackoverflow.com/questions/24349532
复制相似问题