我在这里研究了所有答案(https://stackoverflow.com/a/2191026),但即使@davydepauw 和@emeraldjava 建议的最清晰的代码也不起作用......下面的代码不会选择/取消选择PHP 代码中存在的框。
echo "<form action=$fileName method='post'>";
...
<script language='JavaScript'>
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
}
else {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = false;
});
}
});
</script>";
...
// This should select/deselect all checkboxes below:
echo "<input type='checkbox' name='select-all' id='select-all' />";
...
// The below is in the WHILE loop fetching data from MySQL:
echo "<input type='checkbox' name='IndustryID' value='" . $row['IndustryID'] . "'>";
...
</form>
对于@DavidThomas 请求,以下是呈现的代码:
<body>
<script language='JavaScript'>
$('#select-all').click(function(event) {
if(this.checked) {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = true;
});
}
else {
// Iterate each checkbox
$(':checkbox').each(function() {
this.checked = false;
});
}
});
</script>
...
<form action=XXX.php method='post'>
...
<input type='checkbox' name='select-all' id='select-all' />
...
<input type='checkbox' name='IndustryID' value='3'>
...
<input type='checkbox' name='IndustryID' value='5'>
...
<input type='checkbox' name='IndustryID' value='148'>
...
</form>
</body>