2016-09-15 28 views
1

這裏我有一個按鈕,用戶單擊它添加一個帶有2個radioButton的問題是/否,因爲用戶選擇一個值,如果單擊該按鈕,它將消失再次添加新的radioButton。我想要一個解決方案,即使單擊按鈕並添加新的radioButtons,選中的radioButton的值也會被檢查爲可見。我試圖讓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>

+0

寫一個元素的innerHTML將首先摧毀元素的所有孩子,後來重新創建他們 - 爲此你失去任何檢查狀態變化由用戶製作,因爲你不再有相同的單選按鈕,而是新的。使用不同的方法來添加新的單選按鈕,而不是innerHTML。 (如果你不知道,請先去研究。) – CBroe

回答

0

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>

+0

你是一個很棒的人,謝謝! –

+0

@CSStudent歡迎您;) –

0

您可以包括你的功能融入其中將存儲的包裝的id你需要,請致電myFunction如果有存儲的有效idclick它來檢查它。

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(); 
    } 
} 
0

請嘗試以下;

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

測試和工作。

相關問題