mri*_*ted 1 javascript php checkbox jquery
我已经在这里研究了所有的答案(/sf/answers/153371851/),但即使@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>
Run Code Online (Sandbox Code Playgroud)
对于@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>
Run Code Online (Sandbox Code Playgroud)
您必须将所有内容放在document.ready事件中,否则代码将在元素不存在时运行,并且没有要附加的元素并使用正确的脚本标记
<script type="text/javascript">
$(function(){
$('#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>
Run Code Online (Sandbox Code Playgroud)