如何从单选按钮列表使用JavaScript找到选定项目 [英] How to Find selected item from radiobutton list using javascript

查看:102
本文介绍了如何从单选按钮列表使用JavaScript找到选定项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用javascript从单选按钮列表中找到选择的项目...
这里是我的code

I need to find selected item from radiobutton list using javascript... Here is my code

  <asp:RadioButtonList name="test" ID="RadioButtonList1"  runat="server">
    <asp:ListItem Text="List1" Value="1"></asp:ListItem>
    <asp:ListItem Text="List2" Value="3"></asp:ListItem>
    </asp:RadioButtonList>
    <asp:Button Text="test" runat="server" OnClientClick=" GetListItem()" />

脚本:

<script type="text/javascript" language="javascript">
function GetListItem() {
    var id = document.getElementById("<%=RadioButtonList1.ClientID%>");
    alert(id.selectedItem.value())//Error: 'selectedItem' is null or not an object;
}

我如何才能找到将selectedItem从该列表

How can i find selectedItem from that list

推荐答案

下面是完成这一个相当简单的方式。如果你想找到选中的列表项,当用户点击,在单选按钮列表与JavaScript函数添加onclick属性,以每个项目的点击列表项时调用。在这个参数将清单项目传递给javascript函数:

Here's a fairly straightforward way of accomplishing this. If you want to find the selected list item when the user clicks, add an onclick attribute to each of the items in the RadioButtonList with the javascript function to call when the list item is clicked. The "this" parameter will pass the list item to the javascript function:

<asp:RadioButtonList name="test" ID="RadioButtonList1"  runat="server">
<asp:ListItem Text="List1" Value="1" onclick="myListItemClick(this);"></asp:ListItem>
<asp:ListItem Text="List2" Value="3" onclick="myListItemClick(this);"></asp:ListItem>
</asp:RadioButtonList>

注意的onclick属性不是由ASP.NET智能感知列表项管制的认可,但它仍会触发客户端的JavaScript函数。

Note that the 'onclick' attribute is not recognized by ASP.NET intellisense for ListItem controls, but it will still fire the client-side javascript function.

现在在你的JavaScript函数:

Now in your javascript function:

function myListItemClick(e) {
    alert('Selected value: ' + e.value);
}

请务必将值属性添加到您的所有列表项,这样才能正常工作(因为你已经做了)。

Make sure to add the "Value" attribute to all of your list items for this to work properly (as you have already done).

如果你不想这样做,当用户点击,就可以完成这种方式。在您的标记:

If you don't want to do this when the user clicks, you can accomplish it this way. In your markup:

<script type="text/javascript" language="javascript">
        var radioList = '<%= RadioButtonList1.ClientID %>';
</script>

然后在您的javascript:

Then in your javascript:

function getSelectedListItem() {
   var radioButtonList = document.getElementById(radioList);
   var listItems = radioButtonlist.getElementsByTagName("input");
   for (var i = 0; i < listItems.length; i++) {
       if (listItems[i].checked) {
          alert("Selected value: " + listItems[i].value);
       }
   }
}

这篇关于如何从单选按钮列表使用JavaScript找到选定项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆