但願這不是一個重複的,所以請大家多多包涵。設置複選框,檢查了頁面刷新基於PHP關閉條件的
我有一個表單,它是一系列在數據庫中設置布爾值從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>
你可以從我的代碼中看到的正是我想觸發選擇/取消所有值的邏輯改變。我只是不知道這樣做的正確語法。
預先感謝您。
爲此使用三元運算符 –
Fred,使我變得無知......我不知道三元運算符是什麼。 – Murphy1976
php => http://php.net/manual/en/language.operators.comparison.php「Ternary ...」;-)例如:$ action =(empty($ _ POST ['action']))? 'default':$ _POST ['action'];' - 你可以用'isset'替換它。 –