I have radio inputs, if I click on an input, then after post, all the other inputs go to "checked", I don't understand why, here is my code:
foreach ($tab_stickers_stored as $key => $value) {
<input 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 = "";
});
});
Thank you
CodePudding user response:
Your inputs have different id
attributes, but they all have the same name
. It is the name
that determines what gets submitted, as you have already discovered without realising it when you wrote this line:
<?php if (isset($_POST['switch_sticker'])){echo 'checked="checked"';}?>
That if
statement has nothing in it which varies around the loop; it looks at the same value $_POST['switch_sticker']
every time.
The JavaScript code, meanwhile, is essentially irrelevant to the question, because it only changes the value
of various elements. Those will show up as the value of the $_POST['switch_sticker']
variable, but because there's only one variable and lots of values, it will just end up with the last one in the list.
The solution is to give each of your checkboxes their own name
, like you give them their own value
: name="switch_sticker_<?=$key?>"
. Then look for that name in the PHP: <?php if (isset($_POST['switch_sticker_' . $key])){echo 'checked="checked"';}?>
.
You can also use names in the form something[something_else]
, e.g. name="switch_sticker[<?=$key?>]"
and <?php if (isset($_POST['switch_sticker'][$key])){echo 'checked="checked"';}?>
. That will cause PHP to create an array when they're submitted, which is a bit nicer to work with - you can write things like foreach ( $_POST['switch_sticker'] as $submittedKey => $submittedValue ) { ... }
.