使用 Javascript 在表中设置复选框
尝试在表格内设置一个复选框。我认为这会很简单,并且类似于以表格形式进行。
我可以使用表单成功完成此操作,但当复选框位于表格中时会卡住。
当复选框处于我使用的表单中时:
<form name="access_menu_form">
<input type="checkbox" name="mybox_name" id="mybox_id" value="1">
</form>
document.access_menu_form.mybox_name.checked == true
效果很好!
我知道我错过了关于 DOM 的一个关键点。尝试设置表中的复选框失败,使用类似的技术失败:
我的表:
<table name="access_table">
<thead>
<tr>
<th>Area</th>
<th>Item</th>
<th>Access</th>
</tr>
</thead>
<tr>
<td><input type="checkbox" name="mybox_name" id="mybox_id" value="1"></td>
<td><input type="checkbox" name="mybox1_name" id="mybox1_id" value="1"></td>
<td></td>
</tr>
</table>
我的脚本
document.access_table.mybox_name.checked = false;
我收到错误:未捕获的类型错误:无法读取未定义的属性“mybox”
document.mybox_name.checked = false;
我收到错误:未捕获的类型错误:无法设置属性未定义的“检查”
Trying to set a checkbox inside a table. I thought it would be straightforward and similar to doing it in a form.
I can do this successfully with a form , but getting stuck when the checkbox is in a table.
When the checkbox is in a form I use:
<form name="access_menu_form">
<input type="checkbox" name="mybox_name" id="mybox_id" value="1">
</form>
document.access_menu_form.mybox_name.checked == true
Which works great!!
I know I am missing a key point about the DOM. Trying to set a checkbox that I have in table fails using a similar technique which fails:
My table:
<table name="access_table">
<thead>
<tr>
<th>Area</th>
<th>Item</th>
<th>Access</th>
</tr>
</thead>
<tr>
<td><input type="checkbox" name="mybox_name" id="mybox_id" value="1"></td>
<td><input type="checkbox" name="mybox1_name" id="mybox1_id" value="1"></td>
<td></td>
</tr>
</table>
My script
document.access_table.mybox_name.checked = false;
I get the error: Uncaught TypeError: Cannot read property 'mybox' of undefined
document.mybox_name.checked = false;
I get the error: Uncaught TypeError: Cannot set property 'checked' of undefined
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
如果您有 ID,最直接的方法是使用 getElementById:
无论元素位于何处,它始终有效。
If you have IDs, the most straight-forward way is using
getElementById
:It will always work no matter where the element is residing.
当您像这样使用 javascript 时,您通常会访问元素的 id,而不是名称。请尝试以下操作:
要检查值:
要分配值:
When you use javascript like this, you're typically accessing the id of the element, not the name. Try this instead:
To Check the value:
To Assign the value:
尝试使用
document.getElementById('mybox_id').checked = false
!Try it with
document.getElementById('mybox_id').checked = false
!试试这个:
可以在任何地方工作(桌子内部或外部)。
Try this:
Will work anywhere (inside or outside of table).
只需将复选框包装在表单标签中,该标签与表格标签一起包装即可。这将解决您的问题。
Just wrap the checkboxes in a form tag,which is wrapped with the table tag.That will fix your problem.