2017-06-06 96 views
0

我幾乎有這個工作,但有一件事我不能完全弄清楚: 我想要做的是在飛行中創建一個單選按鈕列表。但是,當我這樣做時,它會每次創建一個收音機框,以便我可以選擇所有答案。我如何創建一個輸入,它有4個選項,這樣我只能選擇一個而不是全部?即時創建單選按鈕列表

function questionAnswers() { 
    let arr = Object.values(questionList[i].answers) 
    for (var a in arr){ 
    let checkbox = document.createElement('input') 
    let label = document.createElement('label') 
    label.appendChild(document.createTextNode(arr[a])) 
    checkbox.type = 'radio'; 
    answerSection.appendChild(checkbox); 
    answerSection.appendChild(label) 
    } 
} 
+2

收音機按名稱分組。給所有人分配相同的名字... –

+0

這[示例](https://stackoverflow.com/questions/28543752/multiple-radio-button-groups-in-one-form)將很方便 – lilixiaocc

回答

0

分配相同的名字給兩個或更多的無線電它們分組:

function questionAnswers() { 
 
    let arr = ["shark","tiger","lion"]; 
 
    let answerSection=document.body; 
 
    for (var a in arr){ 
 
    let checkbox = document.createElement('input') 
 
    let label = document.createElement('label') 
 
    label.appendChild(document.createTextNode(arr[a])) 
 
    checkbox.type = 'radio'; 
 
    checkbox.name="animal"; 
 
    answerSection.appendChild(checkbox); 
 
    answerSection.appendChild(label) 
 
    } 
 
} 
 

 
window.onload=questionAnswers;

如果你有多個無線電,可以指定隨機的名字,如:

var randname=""+Math.floor(Math.random()*10000); 
+0

儘可能我可以看到你只添加在這行:'checkbox.name =「animal」;'我現在已經完成了這個工作。你能解釋爲什麼嗎? –

+0

@Theworm *爲兩個或更多無線電組分配相同名稱* –

0

爲所有單選按鈕命名。

function questionAnswers() { 
 
    let arr = Object.values(questionList[i].answers) 
 
    for (var a in arr){ 
 
    let checkbox = document.createElement('input') 
 
    let label = document.createElement('label') 
 
    label.appendChild(document.createTextNode(arr[a])) 
 
    checkbox.type = 'radio'; 
 
    checkbox.name = "myradio"; 
 
    answerSection.appendChild(checkbox); 
 
    answerSection.appendChild(label) 
 
    } 
 
}