0

I almost have this working but one thing I cant quite figure out: What I'm trying to do is create a radio button list on the fly. However, when I do this it creates a radio box each time so all my answers can be selected. How can I create one input, that has 4 options so that I can only select one instead of them all?

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)
  }
}
The worm
  • 5,580
  • 14
  • 36
  • 49

2 Answers2

0

Assigning the same name to two or more radios groups them:

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;

If you have multiple radios, you may assign random names, like:

var randname=""+Math.floor(Math.random()*10000);
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

Give same name to all the radio buttons.

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)
  }
}
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40