您好,我如何使用queryselector从单选按钮读取两个值并将这些值存储在javascript中的数组中。下面的代码示例是:
<input type="radio" name="one" value="correct" class="firstRow"> Option 1 Mark 1: $650
<input type="radio" name="two" value="incorrect" class="secondRow"> Option 1 Mark 2: Twitter<br>
<input type="radio" name="one" value="incorrect" class="firstRow"> Option 2 Mark 1:$550
<input type="radio" name="two" value="incorrect" class="secondRow"> Option 2 Mark 2:Google<br>
<input type="radio" name="one" value="incorrect" class="firstRow"> Option 3 Mark 1:$650
<input type="radio" name="two" value="correct" class="secondRow"> Option 3 Mark 2:$650<br>
<!--button -->
<input type="button" value="Submit & Next Question" onclick="getAnswer3(this.form)" class="firstRow">
<input type="button" value="Cancel & Clear Selection" onclick="clearOptions(this.form)">
JavaScript我的想法:
function getAnswer3(form) {
var result = [];
//this only reads one value but i need to read 2 values..
var checked = form.querySelector("input[type=radio]:checked");
if(!checked) {
alert('Please select 2 answers..');
}
else{
//reads the values
}
//stores the values in the array..
}
最佳答案
您需要form.querySelectorAll("input[type=radio]:checked");
请记住,从querySelectorAll
返回的内容实际上不是数组,因此没有典型数组所具有的任何特别有趣且简单的帮助器方法。
它确实有长度。
但是,if checked
不会有帮助。
您总是会找回NodeList
。
该列表的长度=== 0,但仍将是一个列表(因此仍通过检查以查看其是否存在)。检查长度是否小于2。