Sur*_*esh 4 asp.net radiobuttonlist
我需要使用javascript从radiobutton列表中找到所选项目...这是我的代码
<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()" />
Run Code Online (Sandbox Code Playgroud)
脚本:
<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;
}
Run Code Online (Sandbox Code Playgroud)
如何从该列表中找到selectedItem
这是一种相当简单的方法来实现这一目标.如果要在用户单击时找到所选列表项,请在单击列表项时使用javascript函数向RadioButtonList中的每个项添加onclick属性."this"参数将列表项传递给javascript函数:
<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>
Run Code Online (Sandbox Code Playgroud)
请注意,用于ListItem控件的ASP.NET intellisense无法识别'onclick'属性,但它仍将触发客户端javascript函数.
现在在你的javascript函数中:
function myListItemClick(e) {
alert('Selected value: ' + e.value);
}
Run Code Online (Sandbox Code Playgroud)
确保将"值"属性添加到所有列表项中,以使其正常工作(如您所做).
如果您不想在用户点击时执行此操作,则可以通过这种方式完成此操作.在你的标记中:
<script type="text/javascript" language="javascript">
var radioList = '<%= RadioButtonList1.ClientID %>';
</script>
Run Code Online (Sandbox Code Playgroud)
然后在你的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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以尝试使用以下JavaScript代码.
function GetListItem() {
var radioButtonlist = document.getElementsByName("<%=RadioButtonList1.ClientID%>");
for (var x = 0; x < radioButtonlist.length; x++) {
if (radioButtonlist[x].checked) {
alert("Selected item Value " + radioButtonlist[x].value);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50368 次 |
| 最近记录: |