我有無線電輸入,如果我點擊一個輸入,然后在發布后,所有其他輸入都會“檢查”,我不明白為什么,這是我的代碼:
foreach ($tab_stickers_stored as $key => $value) {
<input class="form-check-input switch_sticker" type="checkbox" id="switch_sticker_<?=$key?>" name="switch_sticker" value="<?= $key ?>"
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>>
}
$(".switch_sticker").on('change', function() {
var index = $(this).val();
$("input[name='switch_sticker']:checked").each(function(){
if ($("#switch_sticker_" index).is(':checked')) {
var temp = document.getElementById('largeur_sticker_' index).value;
document.getElementById('largeur_sticker_' index).value = document.getElementById('longueur_sticker_' index).value;
document.getElementById('longueur_sticker_' index).value = temp;
} else {
var temp = document.getElementById('longueur_sticker_' index).value;
document.getElementById('longueur_sticker_' index).value = document.getElementById('largeur_sticker_' index).value;;
document.getElementById('largeur_sticker_' index).value = temp;
}
index = "";
});
});
謝謝
uj5u.com熱心網友回復:
您的輸入具有不同的id屬性,但它們都具有相同的name. 它name決定了提交的內容,正如您在撰寫此行時已經發現而沒有意識到的那樣:
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>
該if陳述句中沒有任何內容在回圈中有所不同;$_POST['switch_sticker']它每次都查看相同的值。
同時,JavaScript 代碼本質上與問題無關,因為它只會改變value各種元素的值。這些將顯示為$_POST['switch_sticker']變數的值,但因為只有一個變數和很多值,所以它只會以串列中的最后一個結束。
解決方案是給每個復選框自己的復選框name,就像您給他們自己的一樣value:name="switch_sticker_<?=$key?>"。然后在 PHP: 中查找該名稱<?php if (isset($_POST['switch_sticker_' . $key])){echo 'checked="checked"';}?>。
您還可以使用 形式的名稱something[something_else],例如name="switch_sticker[<?=$key?>]"和<?php if (isset($_POST['switch_sticker'][$key])){echo 'checked="checked"';}?>。這將導致 PHP 在提交時創建一個陣列,這樣使用起來會更好一些 - 你可以撰寫類似foreach ( $_POST['switch_sticker'] as $submittedKey => $submittedValue ) { ... }.
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/485393.html
