我试图从一系列复选框中获取所有已检查输入选项的值,并查找是否有任何已检查的值与特定字符串匹配:
function admissible() {
var b = 4;
var answer = '';
var elementsList = document.querySelectorAll("#question5" + " input:checked");
//get the selected checkbox values for the missing elements
if (elementsList.length >= 0) { //Code works only if some checkbox is checked
if ((elementsList.indexOf("photo") > -1) || (elementsList.indexOf("name") > -1)) { //yes
answer = 'yes';
} else {
answer = 'no';
}
} else {
//display error: you must select a value
}
console.log(answer);
}Run Code Online (Sandbox Code Playgroud)
<div class="questionholder" id="question5">
<div>
<h5>Select all elements</h5>
<input class="input5" type="checkbox" id="elementName" name="element" value="name"><label for="elementName"><p class="radioChoice">Name</p></label>
<input class="input5" type="checkbox" id="elementPhoto" name="element" value="photo"><label for="elementPhoto"><p class="radioChoice">Photo</p></label>
<input class="input5" type="checkbox" id="elementSignature" name="element" value="signature"><label for="elementSignature"><p class="radioChoice">Signature</p></label>
</div>
<div class="holdButtons">
<a class="text2button" onclick="admissible()">Next</a>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
elementsList似乎不存储复选框的值.我该如何解决这个问题?
这段代码中有多个错误。我还做了一些更改以使其更简单。
.indexOf()not .indexOF()。像这样的小错别字可能会毁掉你的整个代码。document.querySelectorAll,你只需要input:checked。#question5是完全不必要的(因为没有一个值的 id 为question5)。.querySelectorAll返回一个NodeList,它更像是一个对象而不是一个数组。因此,.indexOf()对其不起作用。您必须使用for循环或.forEach()像我在下面的代码片段中所做的那样。answerto "no",如果它找到照片或名称,它将将该值设置为(这比为此声明"yes"更容易更好)。if else下面的代码片段适合您。
function admissible() {
var b = 4;
var answer = 'no';
var elementsList = document.querySelectorAll("input:checked");
//get the selected checkbox values for the missing elements
if (elementsList.length >= 0) { //Code works only if some checkbox is checked
elementsList.forEach(e => {
if (e.value == "photo" || e.value == "name") {
answer = "yes";
}
});
} else {
//display error: you must select a value
}
console.log(answer);
}Run Code Online (Sandbox Code Playgroud)
<div class="questionholder" id="question5">
<div>
<h5>Select all elements</h5>
<input class="input5" type="checkbox" id="elementName" name="element" value="name"><label for="elementName"><p class="radioChoice">Name</p></label>
<input class="input5" type="checkbox" id="elementPhoto" name="element" value="photo"><label for="elementPhoto"><p class="radioChoice">Photo</p></label>
<input class="input5" type="checkbox" id="elementSignature" name="element" value="signature"><label for="elementSignature"><p class="radioChoice">Signature</p></label>
</div>
<div class="holdButtons">
<a class="text2button" onclick="admissible()">Next</a>
</div>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
260 次 |
| 最近记录: |