【问题标题】:How to loop through radio/checkbox inputs and push the id of selected ones to arrays如何循环通过单选/复选框输入并将所选输入的 id 推送到数组
【发布时间】:2017-03-09 00:06:54
【问题描述】:

我已经建立了一个多项选择测验。有些答案有无线电框,其他答案有复选框,因为有多个正确的答案。我之前使用过一个脚本来获取所有 :checked 输入的 id 并将它们放入一个数组中以发送到服务器进行评估。

数组看起来像这样:

userAnswers = [ '1c', '2d', '3a', '3b', '3c', '3d', '4b', '5c', '5d', '6d' ]

我已经成功地通过所有的所有内容循环:检查输入并将其HTML ID添加到数组,但我需要更改数据结构,以便更容易评估服务器上的答案。

我正在尝试将数据结构更改为以下内容:

answers = [
  ['c'], // Question 1 answers
  ['d'], // Question 2 answers
  ['a', 'b', 'c', 'd'], // 3
  ['b'], // 4
  ['c', 'd'], // 5
  ['d'], // 6
]
要执行此操作,我正在尝试创建一个找到的循环:基于它们的[数据问题编号]值检查的输入,然后将其HTML ID添加到数组,然后将该数组添加到数组中以上。

到目前为止,我得到的最接近的是以下内容:

let numberOfQuestions = Assessments.findOne().numQuestions; //returns the number of questions in the quiz e.g '25'
let selectedAnswers = [];

for(let i = 1; i <= numberOfQuestions; i++) {
    let answers = $("input[data-question-number=" + i + "]:checked").attr('id');
}

这几乎是有效的,除了问题是.ATTR()只返回匹配的第一个属性,所以在我有4个复选框的一些问题中,用户可能已检查其中3个,我只会得到第一个还给了我。

如果有人可以帮助我修改它,以便它插入所有 :checked 输入的 id,那将是很棒的。谢谢!

【问题讨论】:

    标签: javascript jquery arrays jquery-selectors


    【解决方案1】:
    let answers = []
    for(let i = 1; i <= numberOfQuestions; i++) {
        let temp = []
        $("input[data-question-number=" + i + "]:checked").each(function() {
           temp.push(this.id)
        });
        answers.push(temp)
    }
    

    【讨论】:

      【解决方案2】:

      您将不得不循环遍历结果元素以逐个获取 id。

      for(let i = 1; i <= numberOfQuestions; i++) {
          let answers = []
          $("input[data-question-number=" + i + "]:checked").each(function() {
            answers.push(this.id)
          });
      }
      

      【讨论】:

      • 谢谢,这绝对有帮助,但我接受的答案 100% 解决了问题。非常感谢
      猜你喜欢
      • 2016-12-19
      • 1970-01-01
      • 2016-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-31
      • 2016-05-14
      相关资源
      最近更新 更多