【发布时间】:2019-02-07 05:42:34
【问题描述】:
代码:
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript">
function displayquestion(a, ignore){
var b = a-1;
var currentInput = '';
var questions = document.getElementsByClassName("questionholder");
var showRequired = document.getElementById("requiredMessage");
if (document.querySelector('input.input' + b) !== null) {
var currentInput = document.querySelector('input.input' + b).value;
}
// Check if question should ignore inputs
if (ignore == 1) { // yes, ignore the inputs so move on to next question
console.log("path 1");
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
} else { //no, don't ignore the inputs
if (currentInput == '') { // the input is blank so show error
console.log("path 2");
showRequired.style.display = "block";
} else { // the input is not blank so move on to next question
console.log("currentInput = " + currentInput);
showRequired.style.display = "none";
for(var i=0; i < questions.length; i++) {
questions[i].style.display = "none";
}
var nextQuestion = document.getElementById("question" + a);
if(nextQuestion !== null) {
nextQuestion.style.display = "block";
}
}
}
}
</script>
</head>
<body>
<div id="requiredMessage" style="display:none"><p>This field is required.</p></div>
<form id="TheForm" style="display:block;">
<div data-toggle="buttons" class="questionholder multiplechoice" id="question10" style="display:block">
<h5>Do you have a surname?</h5>
<input class="input10" type="radio" id="yes" name="sn" value="yes"><label for="relPPTsnyes"><p class="radioChoice">Yes / Oui</p></label>
<input class="input10" type="radio" id="no" name="sn" value="no"><label for="relPPTsnno"><p class="radioChoice">No / Non</p></label><br>
<a class="text2button radio" onclick="displayquestion(11)">Next</a>
</div>
</form>
</body>
</html>
我的 javascript 函数有问题,该函数可用于输入文本字段,但不能用于单选按钮。
简而言之,我有一个包含一对单选按钮和一个下一步按钮的 div。当用户点击下一步时,函数 displayquestion(a) 触发。
该函数检查 currentInput 以查看输入是否为空白。如果为空,则显示错误消息。如果不为空,则隐藏div。
但是,对于单选按钮,无论未选择任何内容、选择否或选择是,currentInput 始终返回“yes”。由于它不是空白的,所以它隐藏了 div。
预期结果应该是在用户做出选择之前一直显示错误消息。只有当用户点击下一步时,它才会隐藏 div。
所以我的问题是,是什么导致了我的问题以及如何解决?
【问题讨论】:
-
那么你需要看看其中一个是否被选中...
-
我该怎么做呢?
标签: javascript html