【发布时间】:2011-09-19 02:32:54
【问题描述】:
希望有人能帮助我克服对 Javascript 的无知。
我有一个包含复选框的表单,还有一个 JS 可以切换选择/取消选择所有框。到目前为止,一切都按预期进行。
工作中的关键是我在此表单中有多组复选框,我想按组选择/取消选择,而不是表单中的所有复选框。这是 php 和 html 的示例。如您所见,表单位于表格中,并且在标题行中有一个执行操作的复选框。 'resources_req' 是表单中复选框元素的名称
<form method="post" name="add_reservation">
<?php for($x=0; $x<count($groups); $x++) : // make seperate display for each group ?>
<div class="group_<?php echo $group_label; ?>">
<table class="res">
<tr>
<!-- form: checkbox all -->
<?php if($make_res == 'enter') : // adds checkbox to check all ?>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<?php endif; ?>
<!-- end form: checkbox all -->
</tr>
...
foreach($resources as $resource) { // for each resource/laptop
$form_start = '<td>';
$form_start .= '<input type="checkbox" name="resources_req[]" value="'.$resource['id'].'"';
$form_start .= ' />';
$form_start .= '</td>';
}
...
</table>
</div>
<?php endfor; // loop for each group ?>
<input type="submit" name="add_reservation" value="Make this reservation" />
</form>
这里是被调用的 JS:
function toggle(source, element) {
checkboxes = document.getElementsByName(element);
for(var i in checkboxes)
checkboxes[i].checked = source.checked;
}
尽我所能,脚本调用中的“this”指的是表单。我想如果我可以将这些组中的每一个放入他们自己的 div 类中,然后我可以以某种方式引用它,但现在我迷路了。任何帮助或建议表示赞赏!
编辑:我征求建议,有人建议我只发布 html:
<form method="post" name="add_reservation">
<div class="group_A">
<table>
<tr>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<th>Name</th>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="1" /></td>
<td>John</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="2" /></td>
<td>Bill</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="3" /></td>
<td>Fred</td>
</tr>
</table>
</div>
<div class="group_b">
<table>
<tr>
<th><input type="checkbox" onClick="toggle(this, 'resources_req[]')" /></th>
<th>Name</th>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="4" /></td>
<td>George</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="5" /></td>
<td>Tom</td>
</tr>
<tr>
<td><input type="checkbox" name="resources_req[]" value="6" /></td>
<td>Raymons</td>
</tr>
</table>
</div>
<input type="submit" name="add_reservation" value="Make this reservation" />
</form>
【问题讨论】:
-
我不知道其他人的想法,但就我而言,如果我不必尝试将您的 PHP 翻译成 HTML,那么提供帮助会容易得多它呈现。
-
@patrick-dw:听从你的建议;查看帖子编辑
-
只是一个建议:你可能会发现 jQuery 在做这类事情时非常有用。
标签: javascript html forms