skip to Main Content

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

2

Answers


  1. I understand your situation. You want the radio button that was selected to remain checked and disabled after form submission when you return to the page. The main issue is that you’re not properly accessing and disabling the radio button after retrieving it from localStorage.

    Here’s how you can modify your code:

    Store the selected radio button value in localStorage when the user selects it.

    function check() {
        var btnPieceRad = document.getElementsByName('img');
        for (var i = 0; i < btnPieceRad.length; i++) {
            if (btnPieceRad[i].checked) {
                var valeur = btnPieceRad[i].value;
                localStorage.setItem("radPiece", valeur);
            }
        }
    }
    

    Make sure to call check() whenever a radio button is selected. You can do this by adding onclick="check()" to your radio buttons (which you already have).

    • Disable the previously selected radio button when the page loads.

    Add the following script to your page:

    window.onload = function() {
        var radPiece = localStorage.getItem("radPiece");
        if (radPiece) {
            var btnPieceRad = document.getElementsByName('img');
            for (var i = 0; i < btnPieceRad.length; i++) {
                if (btnPieceRad[i].value === radPiece) {
                    btnPieceRad[i].checked = true;
                    btnPieceRad[i].disabled = true;
                }
            }
        }
    }
    

    This script runs when the page loads and checks if there’s a saved value in localStorage. If there is, it searches through all radio buttons with the name img, and when it finds the one with the matching value, it sets it as checked and disables it.

    Login or Signup to reply.
  2. Change

    <input type="submit" name="submit" value="${piece.nom}" th:value="'Valider : '+ ${piece.nom}" onclick="saveform()"  />` 
    

    to

    <input type="submit" value="${piece.nom}" th:value="'Valider : '+ ${piece.nom}" />
    

    and

    <input type="radio" name="img" th:value="${piece.img}" onclick="check()"  required>
    

    to

    <input type="radio" name="img" th:value="${piece.img}" required>
    

    Then you delegate – NOTE: this assumes the number of radios do not change between stored in localStorage and retrieved. So perhaps use sessionStorage instead.

    I also assume the value of the radio did not change when reloaded

    window.addEventListener('load',() => {
      const checked = JSON.parse(localStorage.getItem('checked') || '[]'); // get the list
      const rads = document.querySelectorAll('#formP input[name=img]');
      checked.forEach((chk,i) => {
        rads[i].checked = rads[i].disabled = chk); // check and disable
      }
      const form = document.getElementById('formP');
      // form.addEventListener('submit',saveForm); // no longer needed
      form.addEventListener('click',(e) => {
        const tgt = e.target;
        if (!tgt.?name === 'img') return; // not a radio
        rads.forEach((rad,i) => checked[i] = rad.checked; // save the states
        localStorage.setItem('checked',JSON.stringify(checked)); // only place to write
      });
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search