我已經在這裏學習所有的答案(https://stackoverflow.com/a/2191026),但建議由@davydepauw和@emeraldjava不工作...下面的代碼不會選擇,即使最清晰的代碼/取消選擇PHP代碼中的框。JavaScript和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>
你能張貼在jsfiddle.net一個精簡的例子嗎? – Arno 2012-04-18 15:02:34
你的PHP是無關的jQuery和Javascript一般,請出示呈現的HTML,而不是服務器端腳本。 – 2012-04-18 15:03:00
看看這裏:http://api.jquery.com/live/,我覺得你沒有得到的結果,因爲元素創建你的JavaScript之前 – Gerep 2012-04-18 15:04:53