Reputation: 111
I have two different groups of radio buttons that need to be validated before the form can be submitted. I may need to add more options to this in the future, but for now there are 2 groups of Yes/No questions. Here is the code for the radio buttons so far.
<form name=myForm action="test.php" method="post">
<input type="radio" name="question1" id="question1">
<input type="radio" name="question1" id="question1">
<input type="radio" name="question2" id="question2">
<input type="radio" name="question2" id="question2">
<input type="submit" value="Submit">
</form>
So basically looking for a way to make sure an option was selected within each group (question 1 and question 2) before the form can be submitted.
Upvotes: 1
Views: 8834
Reputation: 3312
This problem is really two parts and a side note.
The side note (which isn't relevant to the issue) is that id should always be unique, having two radio's with an id of "question1" is invalid.
Issue one is to check it on the form submission. The easiest way of doing this is to add a "return functName()" to the onsubmit tag of the form.
<form name='myForm' action='test.php' method='post' onsubmit='return validate()'>
Whether the form will submit or not will depend on whether you return true or false in the submission.
The second is to grab the radio boxes and check if they've been selected or not. You can grab the inputs of each radio seelct by using:
document.forms.myForm.nameOfRadioHere
which will supply you with a list of the inputs under that name.
Then you just have to loop through them to check that one of them has .checked as valid.
Example Code:
Javascript:
function validate(){
if (checkRadio("question1") && checkRadio("question2")){
return true;
}else{
alert("Please fill in both radio boxes!");
return false;
}
}
function checkRadio(name){
var radio = document.forms.myForm[name];
for (var option in radio){
if(radio[option].checked){
return true;
}
}
return false;
}
HTML
<form name='myForm' action="test.php" method="post" onsubmit='return validate()'>
<input type="radio" name="question1">
<input type="radio" name="question1">
<input type="radio" name="question2">
<input type="radio" name="question2">
<input type="submit" value="Submit">
</form>
Upvotes: 1