前台用服务器控件CheckBoxList
<asp:CheckBoxList ID="chkSports" runat="server"> </asp:CheckBoxList>
在后台对其赋值
chkSports.Items.Add("苹果"); chkSports.Items.Add("西瓜"); chkSports.Items.Add("橘子"); chkSports.Items.Add("香蕉"); chkSports.Items[2].Selected = true;
在前台界面生成html代码为:
<table id="chkSports"> <tr> <td><input id="chkSports_0" type="checkbox" name="chkSports$0" value="苹果" /><label for="chkSports_0">苹果</label></td> </tr><tr> <td><input id="chkSports_1" type="checkbox" name="chkSports$1" value="西瓜" /><label for="chkSports_1">西瓜</label></td> </tr><tr> <td><input id="chkSports_2" type="checkbox" name="chkSports$2" checked="checked" value="橘子" /><label for="chkSports_2">橘子</label></td> </tr><tr> <td><input id="chkSports_3" type="checkbox" name="chkSports$3" value="香蕉" /><label for="chkSports_3">香蕉</label></td> </tr> </table>
打印checkbox选中的内容:
$("#btnSend").click(function () { //[name^=chkSports]选取属性值以chkSports开头的元素,即是chkSports下的所有元素 $("[name^=chkSports]:checkbox").each(function () { if (this.checked) { alert($(this).val()); } });
此实例是为了更清楚的说明服务器控件CheckBoxList在界面上生成的html情况以及如何在jquery中使用。