如何在添加另一个新的单选按钮时保存单选按钮的值

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

本文关键字:单选按钮 保存 添加 另一个      更新时间:2023-09-26

这里我有一个按钮,当用户单击它添加一个带有2个radioButton是/否的问题,当用户选择一个值时,如果再次单击按钮并添加新的radioButtons,它就会消失。我想要一个解决方案,检查的radioButton的值将是可见的检查,即使按钮被单击和新的radioButtons被添加。我试图使id标签变量,使每个radioButton有一个唯一的id,但它没有任何区别。任何帮助都将非常感激。

<!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>

innerHTML将覆盖!你会失去之前的input状态。
使用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>

您可以将您的功能包含在包装器中,该包装器将存储您需要的id,调用myFunction,如果存储有有效的id,则click检查它。

function myFunctionWrapper() {
    var checked = document.querySelector("#demo > input[type=radio]:checked")
    var checkedID = checked ? checked.id : undefined;
    myFunction();
    if (!!checkedID) {
        document.querySelector("#" + checked.id).click();
    }
}

尝试以下;

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

<script>
var x=0;
var y=0;
function myFunction() {
var html=""; 
for(var i=0;i<x;i++)
{
    if(document.getElementById("radio-"+i).checked)
      html=html+"<input type=radio id=radio-"+i+" name=rad-"+i+" checked> Yes <input type=radio id=radio1-"+i+" name=rad-"+i+"> No <br>";
    else
      html=html+"<input type=radio id=radio-"+i+" name=rad-"+i+"> Yes <input type=radio id=radio1-"+i+" name=rad-"+i+" checked> No <br>";
}
html=html+"<input type=radio id=radio-"+y+" name=rad-"+x+"> Yes <input type=radio id=radio1-"+y+" name=rad-"+x+"> No <br>";
document.getElementById("demo").innerHTML=html;
x++;
y++; 
}
</script>
</body>
</html>

测试正常