Here is my problem: I have radio buttons in a loop, in a form (in spring boot) and I would like the radio button that was checked to remain checked after submitting the form and especially when we return to the choice page , just to not be able to recheck the same choice (in JS). Basically, I make a choice, I submit => it sends me to another page but when I return to my page of choice, the previous choice must be disabled.
Form:
<form action="#" th:action="@{/piece}" modelAttribute="piece" method="post"
id="formP" onsubmit="">
<tr th:each="piece: ${pieces}">
<input type="submit" name="submit" value="${piece.nom}" th:value="'Valider : '+ ${piece.nom}"
onclick="saveform()" />
<label class="radio-image">
<input type="radio" name="img" th:value="${piece.img}" onclick="check()" required>
<img th:src="@{${'/images/'+ piece.img}}" />
</label>
<br>
</tr>
</form>
Function to retrieve the choice in localStorage:
function check() {
var btnPieceRad = document.getElementsByName('img');
for (i = 0; i < btnPieceRad.length; i++) {
if ((btnPieceRad[i].checked)) {
var valeur = btnPieceRad[i].value;
localStorage.setItem("radPiece", valeur);
}
}
}
I try:
function saveform() {
var radPiece = localStorage.getItem("radPiece") ;
radPiece.getElementsByTagName('radio')[radPiece].disabled = true;
}
Without result
Then I got inspired by the subject How do I disable and check which option that I chose in the radio buttons after form submission?
And I do :
function saveform() {
var formPiece = document.getElementsByTagName("form");
formPiece.addEventListener("submit",function(){
var inputs = formPiece[0].getElementsByTagName("input");
for(var i=0; i<inputs.length; i++){
var this_input = inputs[i];
if( this_input.type=="radio") {
this_input.disabled = true;
}
}
});
}
Without result and I have a sneaky error in the console:Uncaught on this line:
formPiece.addEventListener("submit",function()
Thanks for your help