【发布时间】:2017-01-26 16:42:01
【问题描述】:
希望这不是重复的,所以请多多包涵。
我有一个表单,它是一系列复选框,它在数据库中设置一个从 0 到 1 的布尔值,然后在提交时,它获取这些值,更新数据库,然后刷新页面,这样如果值是设置为 0 复选框未选中,如果值为 1,则选中复选框。所有这些都有效 - 我的这部分代码没有问题。
我的问题是,在我的 SUBMIT 按钮上方,我有一个 Select/Deselect All 按钮,如果选择了 ALL,则在页面刷新时,复选框保持选中状态。但是在刷新时,该按钮未被选中,我必须单击它两次才能使复选框取消选中所有前面提到的复选框。
这是我的代码:
<form action="" method="post">
<?php
while( $row = mysql_fetch_array($result) ){
$id = $row['id'];
$active = $row['active'];
$name = $row['name'];
$class = $row['class'];
if($active == '1'){
**IF ANY OF THESE CHECKBOXES ARE ACTIVE, THEN THE SELECT/DESELECT ALL BUTTON SHOULD BE CHECKED -- WHAT IS THE PROPER SYNTAX???**
}
echo "<input type='hidden' name='activate_".$id."' value='0'>";
echo "<label class='switch'><input type='checkbox' class='checkbox' name='activate_".$id."' value='1'";
if($active == '1'){
echo "checked='checked'";
}
echo "/><div class='slider'></div><span>" . $name . "</span></label>";
}
mysql_close();
?>
<label for="select_all" class="selectAllLabel"><input type="checkbox" id="select_all"/> Activate/Deactivate All</label>
<input type="submit" class="submit" name="submit" value="Update Active Roster">
</form>
<iframe src="index.html" width="376" height="260" style="border: 0;"></iframe>
<?php
if(isset($_POST['submit'])){
require "config.php";
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
for ($i = 1; $i<count($_POST); $i++){
$sql = "UPDATE roster SET active = ".$_POST["activate_$i"]." WHERE id = ".$i;
if ($conn->query($sql) === TRUE) {
echo "";
} else {
echo $conn->error;
}
}
$conn->close();
echo "<meta http-equiv='refresh' content='0'>";
}
?>
<script>
$(document).ready(function(){
//select all checkboxes
$("#select_all").change(function(){ //"select all" change
var status = this.checked; // "select all" checked status
$('.checkbox').each(function(){ //iterate all listed checkbox items
this.checked = status; //change ".checkbox" checked status
});
});
$('.checkbox').change(function(){ //".checkbox" change
//uncheck "select all", if one of the listed checkbox item is unchecked
if(this.checked == false){ //if this item is unchecked
$("#select_all")[0].checked = false; //change "select all" checked status to false
}
//check "select all" if all checkbox items are checked
if ($('.checkbox:checked').length == $('.checkbox').length ){
$("#select_all")[0].checked = true; //change "select all" checked status to true
}
});
});
</script>
您可以从我的代码中确切地看到我希望逻辑触发 Select/Deselect All 值被更改的位置。我只是不知道这样做的正确语法。
提前谢谢你。
【问题讨论】:
-
为此使用三元运算符
-
弗雷德,让我无知...我不知道三元运算符是什么。
-
php => php.net/manual/en/language.operators.comparison.php 在“三元...”下 ;-) 即那里的例子:
$action = (empty($_POST['action'])) ? 'default' : $_POST['action'];- 你可以用isset替换它。 -
谢谢你@Fred-ii-你能发布一个答案,所以我可以给你信用,拜托。
标签: javascript php jquery html checkbox