使用JavaScript在asp.net中验证radiobuttonlist

问题描述:

我必须使用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" />