My code should pop up an alert if radio button is not selected. My problem is that it only pops up if you have choosen one question. For example, i selected an answer in question 1 but not on question 2. So it gives an alert: Must select question number two! But my problem is that, if you don't select any, it doesn't alert me anything. If i haven't selected anything, it should pop up, 2 alerts, Must select question number one and after that, another alert, must select question number 2! any help would be appreciated, thanks!
<html>
<head>
<script>
function checkAnswers(){
var retval = false;
var inputs = document.getElementsByTagName('input');
for(i=0;i<inputs.length;i++){
var inputName = inputs[i].getAttribute('name');
// var msg = document.getElementById('msg-' + inputName);
var checker = document.getElementsByName(inputName);
var counter = false;
for(j=0;j<checker.length;j++){
if(checker[j].checked == true){
counter = true;
i += 4;
break;
}
}
if(counter == false){
alert("Must answer question number" + " " + inputName + "!");
retval = false;
i += 4;
}
}
return retval;
}
</script>
</head>
<body>
<form name="myForm" onsubmit="return checkAnswers()" id="form">
<h1>QUESTIONS</h1>
<h3>Question No. 1.)</h3>What makes you smile?<br />
<input name="one" type="radio" value="yes" />A. Burger<br />
<input name="one" type="radio" value="no" />B. Pizza <br />
<input name="one" type="radio" value="no" />C.Sunrise <br />
<input name="one" type="radio" value="no" />D. Kitkat<br />
<span id="msg-one"></span><br />
<h3>Question No. 2.)</h3>What's your favorite day?<br />
<input name="two" type="radio" value="no" />A. Hi<br />
<input name="two" type="radio" value="yes" />B. Hello<br />
<input name="two" type="radio" value="no" />C. Ahh<br />
<input name="two" type="radio" value="no" />D. Kitkat<br />
<span id="msg-two"></span><br/>
<input type="button" name='submit' value="Submit" /><br />
<span id="score"></span><br />
</form>
</body>
</html>
You have nested for loops, both using the variable "i". Try changing this so each loop has an individual (ideally descriptive) variable name.
Since you added jquery , I'll suggest a solution using jQuery:
function checkAnswers() {
var questions = {};
$('#form input[type="radio"]').each(function() {
// add all questions
questions[this.name] = true;
}).filter(":checked").each(function() {
// remove questions that have an answer
delete questions[this.name];
});
for (var k in questions) {
alert("Must answer question number " + k + "!");
}
}
questions
is used here to mimic a set .
But your submit button also should have the type submit
, not button
or you need to add a onclick
handler:
<input type="submit" name='submit' value="Submit" />
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.