【问题标题】:Creating a radio button list on the fly即时创建单选按钮列表
【发布时间】:2017-11-07 18:46:22
【问题描述】:

我几乎可以完成这项工作,但有一件事我无法弄清楚: 我想要做的是动态创建一个单选按钮列表。但是,当我这样做时,它每次都会创建一个单选框,以便可以选择我的所有答案。如何创建一个输入,它有 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)
  }
}

【问题讨论】:

  • 收音机按名称分组。为它们分配相同的名称...
  • 这个example 会很方便

标签: javascript radio-button


【解决方案1】:

为两个或多个无线电组分配相同的名称:

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);

【讨论】:

  • 据我所知,您只在这一行中添加了:checkbox.name="animal"; 我现在已经这样做了,它可以工作了。你能解释一下为什么吗?
  • @Theworm 将相同的名称分配给两个或多个无线电组
【解决方案2】:

为所有单选按钮指定相同的名称。

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)
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-19
    相关资源
    最近更新 更多