Reputation: 118
I coded a form that can post information to another page where it is processed. I wanted to ask users if there are options that were not selected. My form looks like this:
<form action="answers-of-brain-teaser-questions.php" method="post">
<div>
<div>Question 1</div>
<input name="q1" type="radio" value="1">A. 1
<br />
<input name="q1" type="radio" value="2">B. 4
<br />
<input name="q1" type="radio" value="3">C. 3
<br />
<input name="q1" type="radio" value="4">D. 2
</div>
<div>
<div id="question">Question 2</div>
<input name="q2" type="radio" value="5">A. 1
<br />
<input name="q2" type="radio" value="6">B. 2
<br />
<input name="q2" type="radio" value="7">C. 3
<br />
<input name="q2" type="radio" value="8">D. 4
</div>
</form>
How can I show users a message if some radio buttons are clicked. I only want to show a message if a question has no selected answer (no radio button is selected). For example, if no option is selected for question 2.
Upvotes: 0
Views: 207
Reputation: 7388
If you have no access to JQuery and want to support browsers not supporting required
, you can use something like this:
var names = new Array("q1", "q2");
var notSelected = new Array();
var checked = "";
for(var i = 0; i < names.length; ++i) {
var current = getElementsByName(names[i]);
for(var j = 0; j < current.length; ++j) {
if(current[j].checked) {
checked = names[i];
}
}
if(names[i] !== checked)
notSelected.push(names[i]);
}
if(notSelected.length>0)
alert("You have to select the following radiogroups: "+notSelected.join(", "));
Upvotes: 1
Reputation: 173
The easiest way to do this is with the built-in HTML5 attribute called required which tells the user that he has left a field (in our case the radio button).
An example how to use it:
<!DOCTYPE HTML>
<html>
<body>
<form id="exampleForm" action="#" method="get">
<input name="q1" type="radio" required="required" value="4">test<br />
<input name="q1" type="radio" required="required" value="4">test<br />
<input name="q1" type="radio" required="required" value="4">test<br />
<input name="sform" type="submit">
</form>
</body>
</html>
Upvotes: 2
Reputation: 595
If you want to validate it via jquery it will go like- //in script add jquery-min.js
function validate(){
if($("input[name=q2]:checked").length > 0) {
//Is Valid
}
}
<form action="answers-of-brain-teaser-questions.php" method="post" onsubmit="validate()">
<div>
<div>Question 1</div>
<input name="q1" type="radio" value="1">A. 1
<br />
<input name="q1" type="radio" value="2">B. 4
<br />
<input name="q1" type="radio" value="3">C. 3
<br />
<input name="q1" type="radio" value="4">D. 2
</div>
<div>
<div id="question">Question 2</div>
<input name="q2" type="radio" value="5">A. 1
<br />
<input name="q2" type="radio" value="6">B. 2
<br />
<input name="q2" type="radio" value="7">C. 3
<br />
<input name="q2" type="radio" value="8">D. 4
</div>
</form>
And if you want to do it in php page- then check it via-
if(!isset($_POST['q2'})){
//your msg to user
}
Upvotes: 0