JQuery设置与获取RadioButtonList和CheckBoxList的值

时间:2021-12-31 00:54:27

有这样一个问题,要获取ASP.NET控件RadioButtonList的值,首先想到的就是$("#<%=RadioButtonList1.ClientID %>").val();结果返回为空。于是在浏览器查看HTML文本:

JQuery设置与获取RadioButtonList和CheckBoxList的值

发现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);
});
});

CheckBoxList可能会多选,所有需要遍历选中的项。上面的几句js代码顺利地取到了值。

JQuery设置与获取RadioButtonList和CheckBoxList的值

设置默认选中的值:

             //设置RadioButtonList1第二项选中
$("#<%=RadioButtonList1.ClientID %>").find("input[type='radio']")[].checked = true; //设置CheckBoxList1第二、三项选中
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[].checked = true;
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[].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']")[].checked = true; //设置CheckBoxList1第二、三项选中
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[].checked = true;
$("#<%=CheckBoxList1.ClientID %>").find("input[type='checkbox']")[].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="">北京</asp:ListItem>
<asp:ListItem Value="">上海</asp:ListItem>
<asp:ListItem Value="">南京</asp:ListItem>
</asp:RadioButtonList>
<input id="btnSelRadioList" type="button" value="RadioButtonList选中项" />
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem Value="">北京</asp:ListItem>
<asp:ListItem Value="">上海</asp:ListItem>
<asp:ListItem Value="">南京</asp:ListItem>
</asp:CheckBoxList>
<input id="btnSelCheckBoxList" type="button" value="CheckBoxList选中项" />