Home > Back-end >  How do I disable and check which option that I chose in the radio buttons after form submission?
How do I disable and check which option that I chose in the radio buttons after form submission?

Time:06-01

I need to disable the radio buttons and show the chosen radio button checked after form submission. Therefore after form submission user can see checked radio button but he/she cannot change it without resetting. How can I do this?

<form th:action="@{/addRating}"  th:object="${ratings}" method="post">
            <div ></div>
 <div>

   <input type="radio" id="rCorrect" name="rg1"  value=" 1" th:field="*{ratingValue}">
   <label for="rCorrect"  ></label>Rate as a correct answer

 </div><br>

  <div>
   <input   type="radio" id="rWrong" name="rg2"  value="-1" th:field="*{ratingValue}">
    <label for="rWrong" ></label>Rate as a incorrect answer
  </div>

   <input  type="reset" value="Reset">
   <input type="submit" value="Submit">

 </form>

CodePudding user response:

You can add the disabled attribute to the radio buttons that are not selected. You should do this after form submission.

Would be something like this:

let uncheckedRadioButtons = 
   document.querySelectorAll('input[type="radio"]:checked'); 
for(let radioBtn of uncheckedRadioButtons){
   radioBtn.setAttribute("disabled", "")
}

CodePudding user response:

You have to disable the form elements using javascript event "onSubmit".

//non jQuery mode
var form = document.getElementsByTagName("form");

form.addEventListener("submit",function(event){

    var inputs = form[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;
        }
    }
});


//jQuery Mode
$("form").on("submit",function(){
    $(this).find('input[type="radio"]').prop("disabled",true);
});

UPDATE: If the form is not submited via AJAX (that i think is the case) then you have to do this in the server. you have to write the HTML of the form pre-filled with the correct answer and with the attribute "disabled" or "readonly" set to all the radio inputs and also to the submit button should be set "disabled" to prevent submiting again. In the reset button in this case you have to addEventListener in javascript to re-enable submiting and radio buttons.

  • Related