需要回答多个单选按钮才能转到下一页 HTML

Require answers to multiple radio buttons to go to next page HTML

我正在设置一个多页 survey/study,每页有 2 个多选单选按钮问题(第一页除外,不需要回答)。我有一个下一个功能,用于检查以确保已给出答案。它有效,但是当传递两个值以便检查两个问题时,它只检查其中一个。我使用 console.log 来显示通过函数传递的名称,并且只传递了一个名称。我可以通过只回答一个问题进入下一页,即使它不是根据控制台日志中的名称通过函数的那个​​。我怎样才能让它检查我在 onclick 中指定的所有问题?

这里是 Continue 按钮的代码,带有 onclick 的 next() 函数。当我传递两个名称时,它只会检查 2 个中的 1 个。

<input type="button" value="Continue" onclick="next('Q1Answer','Q1Rating');"/>

这些是单选按钮:

问题 1

<input name="Q1Answer" type="radio" value="Right" /> Right&emsp;
<input name="Q1Answer" type="radio" value="Wrong" /> Wrong

问题 2

Less confident &nbsp; &nbsp; 
    <input class="rating" name="Qrating" type="radio" id="v1" value="1" />
    <input class="rating" name="Qrating" type="radio" id="v2" value="2" />
    <input class="rating" name="Qrating" type="radio" id="v3" value="3" />
    <input class="rating" name="Qrating" type="radio" id="v4" value="4" />
    <input class="rating" name="Qrating" type="radio" id="v5" value="5" />
&nbsp; &nbsp; More confident

这是我下一个功能的当前版本。我添加了一个 for 循环以尝试让它遍历传递给它的所有项目,但这并没有解决问题(它在没有循环的情况下以相同的方式工作)。此代码位于我在 HTML 代码中调用的 javascript 文件中。

function next(name) {
    for (i in name) {
        if (name.startsWith('Q')) {
            if (!document.querySelectorAll('input[name]:checked').length) {
                alert("Please answer the question.");
                return;
}
}
}   
    current++;
    swap(effectivePage(current - 1), effectivePage(current));
}

(swap和effectivePage是其他的跳到下一页的函数,需要的话我可以加进去测试)

我已经使用名称作为标识符,但可以很容易地用 ID 替换,如果这样可以更容易的话。我使用了 startsWith if 条件,以便只检查实际问题。

我有基本的 HTML 知识,但 Javascript 完全不懂 Javascript 除了我自学的知识,所以我希望解决方案很简单一.

所以我设法找到了 2 个问题,这些问题使您的代码无法按照您想要的方式执行。当您在 HTML 中创建下一个调用时,您试图传入多个名称字符串,但 next 函数只接受一个参数。这意味着你的调用只会得到第一个字符串来检查,在这种情况下是 Q1Answer。如果将传递给字符串数组的值更改,则可以对所需的所有名称执行检查。此外,请务必在下一次调用中传递要检查的输入的确切名称。如果这些名称不正确,您的代码将导致用户永远无法访问下一页,因为它会认为该输入从未被选中(因为它根本不会在页面上找到该输入)。

其次,当您使用查询选择器执行检查时,您没有检查任何特定名称,因此即使它应该检查第二个输入标记,它也总是找到选定的第一个值。我修改了该检查,现在专门查找传入的名称,因此它只会与有问题的输入匹配(即,第一遍将检查 Q1Answer,第二遍将检查 Qrating)。

function next(name) {
  for (i in name) {
    if (name[i].startsWith('Q')) {
      if (!document.querySelectorAll('input[name=' + name[i] + ']:checked').length) {
        alert("Please answer the question.");
        return;
      }
    }
  }
  current++;
  swap(effectivePage(current - 1), effectivePage(current));
}
<input type="button" value="Continue" onclick="next(['Q1Answer','Qrating']);" />

<input name="Q1Answer" type="radio" value="Right" /> Right&emsp;
<input name="Q1Answer" type="radio" value="Wrong" /> Wrong

<br/> Less confident &nbsp; &nbsp;
<input class="rating" name="Qrating" type="radio" id="v1" value="1" />
<input class="rating" name="Qrating" type="radio" id="v2" value="2" />
<input class="rating" name="Qrating" type="radio" id="v3" value="3" />
<input class="rating" name="Qrating" type="radio" id="v4" value="4" />
<input class="rating" name="Qrating" type="radio" id="v5" value="5" /> &nbsp; &nbsp; More confident