循环浏览表单中的所有 html 复选框
本文关键字:html 复选框 浏览 表单 循环 | 更新日期: 2023-09-27 18:30:38
我希望能够遍历表单中的所有html复选框,如果选中它,则执行其他操作。我还想在不使用任何Javascript''jquery的代码中执行此操作。
<form id="form1" runat="server">
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<div>
<table width="850" border="0" cellpadding="0" cellspacing="10" class="Copy" >
<tr>
<td valign="top"><table width="200" border="0" cellspacing="0" cellpadding="3" bgcolor="#f0f4f8">
<tr>
<td width="21"> </td>
<td width="179"><strong>CheckBoxes</strong></td>
</tr>
<tr>
<td><input runat="server" type="checkbox" name="checkbox1" id="checkbox1" /></td>
<td>checkbox1</td>
</tr>
<tr>
<td><input runat="server" type="checkbox" name="checkbox2" id="checkbox2" /></td>
<td>checkbox2</td>
</tr>
<tr>
<td><input runat="server" type="checkbox" name="checkbox3" id="checkbox3" /></td>
<td>checkbox3</td>
</tr>
</table>
</div>
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Button" />
</form>
在代码隐藏中,我尝试了几种不同的方法,但我猜测因为它是复选框类型的 HTML 输入控件,它不起作用
foreach (CheckBox chk in Page.Form.Controls.OfType<CheckBox>())
{
if (chk.Checked == true)
{
Label1.Text = "we have checkboxes";
}
else
{
Label1.Text = "Still no checkboxes";
}
}
几种方法:
foreach (Control item in this.form1.Controls)
{
//We just need HtmlInputCheckBox
System.Web.UI.HtmlControls.HtmlInputCheckBox _cbx = item as System.Web.UI.HtmlControls.HtmlInputCheckBox;
if (_cbx != null)
{
if (_cbx.Checked)
{
//Do something:
Response.Write(_cbx.Name + " was checked.<br />");
}
}
}
或
//We just need HtmlInputCheckBox
IEnumerable<Control> _ctrls = from Control n in this.form1.Controls where n as System.Web.UI.HtmlControls.HtmlInputCheckBox != null select n;
if (_ctrls.Count() > 0)
{
foreach (System.Web.UI.HtmlControls.HtmlInputCheckBox item in _ctrls)
{
if (item.Checked)
{
//Do something:
Response.Write(item.Name + " was checked.<br/><br />");
}
}
}
希望这有帮助....
如果您知道复选框的 ID,则可以尝试使用: FindControl
Control.FindControl-Methode (string)
这不是一个很好的解决方案,biut尝试使用它:
bool cFound = true;
while(cFounnd)
{
var cCheckBox = this.FindControl(...);
if(cCheckBox != null)
{
....
}
else
{
cFound = false;
}
}
编辑:也许你试试这个: ControlFinder