CS Student CS Student - 2 months ago 10
HTML Question

how to save the value of radio buttons when another new radio buttons are added

Here I have a button as the user click it add a question with 2 radioButton yes/no as the user choose one value it disappears if the button is clicked again and new radioButtons are added. I want a solution where the value of the checked radioButton will be visible as checked even if the button is clicked and new radioButtons are added. I have tried to make the id tag variable so that each radioButton have a unique id but it does not make any difference. Any help will be very appreciated.



<!DOCTYPE html>
<html>
<body>
<h1>Radio Buttons </h1>
<div id = "demo"> </div>
<br>
<button onclick="myFunction()"> add </button>


<script>
function myFunction() {
document.getElementById("demo").innerHTML += '<br> agree? '+
'<br> <input type="radio" id="x"> yes' + ' <input type="radio" id="y"> No <br>';
}
</script>

</body>
</html>




Answer

innerHTML will overwrite! And you'll loose previous input states.
Instead use Element.insertAdjacentHTML()

<!DOCTYPE html>
<html>
  <body>
    <h1>Radio Buttons </h1>
    <div id = "demo"> </div>
    <br>
    <button onclick="myFunction()"> add </button>


    <script>
      function myFunction() {
        document.getElementById("demo").insertAdjacentHTML("beforeend", '<br> agree? '+
        '<br>  <input type="radio" id="x"> yes' + ' <input type="radio" id="y"> No <br>'); 
      }
    </script>

  </body>
</html>

Comments