要获取ASP.NET控件RadioButtonList的值,首先想到的就是$("#<%=RadioButtonList1.ClientID %>").val();结果返回为空。于是在浏览器查看HTML文本:
发现RadioButtonList和CheckBoxList都被解析为Table,并且每个子项由一个radio(checkbox)和label构成,label保存文本信息。
$(document).ready(function () {
$("#btnSelRadioList").click(function () {
var sValue = $("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']:checked").val();
var sText = $("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']:checked").next().text()
alert(sValue + "|" + sText);
});
$("#btnSelCheckBoxList").click(function () {
var sValue = "";
var sText = "";
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']:checked").each(function () {
sValue += $(this).val() + ";";
sText += $(this).next().text() + ";";
})
alert(sValue + "|" + sText);
});
});
设置默认选中的值:
//设置RadioButtonList1第二项选中
$("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']")[1].checked = true;
//设置CheckBoxList1第二、三项选中
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[1].checked = true;
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[2].checked = true;
完整的代码:
<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script>
$(document).ready(function () {
//设置RadioButtonList1第二项选中
$("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']")[1].checked = true;
//设置CheckBoxList1第二、三项选中
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[1].checked = true;
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[2].checked = true;
$("#btnSelRadioList").click(function () {
var sValue = $("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']:checked").val();
var sText = $("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']:checked").next().text()
alert(sValue + "|" + sText);
});
$("#btnSelCheckBoxList").click(function () {
var sValue = "";
var sText = "";
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']:checked").each(function () {
sValue += $(this).val() + ";";
sText += $(this).next().text() + ";";
})
alert(sValue + "|" + sText);
});
});
</script>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem Value="1">北京</asp:ListItem>
<asp:ListItem Value="2">上海</asp:ListItem>
<asp:ListItem Value="3">南京</asp:ListItem>
</asp:RadioButtonList>
<input id="btnSelRadioList" type="button" value="RadioButtonList选中项" />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="1">北京</asp:ListItem>
<asp:ListItem Value="2">上海</asp:ListItem>
<asp:ListItem Value="3">南京</asp:ListItem>
</asp:CheckBoxList>
<input id="btnSelCheckBoxList" type="button" value="CheckBoxList选中项" />