markm5i
asked on
javascript validate multiple radio buttons
Have a bunch of radio buttons on an ASP page:
q1 with 4 buttons (possible answers)
q2 with 2 buttons
q3 with 4 buttons
etc.
Wondering if there is a quick way of implementing a Javascript function to ensure that all questions have been answered.
Keep in mind that we have approx. 12 pages with 10 questions per page!
q1 with 4 buttons (possible answers)
q2 with 2 buttons
q3 with 4 buttons
etc.
Wondering if there is a quick way of implementing a Javascript function to ensure that all questions have been answered.
Keep in mind that we have approx. 12 pages with 10 questions per page!
refer to the attached example:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
function getElementsByName(f,n){
var e=new Array();
for(var i=0; i < f.elements.length; ++i)
{
if(f.elements[i].name==n)
e[e.length]=f.elements[i];
}
return e;
}
function validate(f)
{
var radioList="q1,q2,q3,q4";
var messages={
"total":4
,"q1":"Question 1 is a required field"
,"q2":"Question 2 is a required field"
,"q3":"Question 3 is a required field"
,"q4":"Question 4 is a required field"
};
radioList=radioList.split(",");
for(var i=0; i < radioList.length; ++i)
{
var chk=false;
var t = getElementsByName(f,radioList[i]);
for( var j=0; j < t.length; ++j)
{
if(t[j].checked)
{
chk=true;
break;
}
}
if( chk )
{
delete(messages[ radioList[i] ]);
--messages.total;
}
}
for( k in messages)
{
if(k!="total")
alert(messages[k]);
}
return (messages.total==0);
}
</script>
</head>
<body>
<form onsubmit="return validate(this)">
<div>Q1:...
<input type="radio" name="q1" value=""/>
<input type="radio" name="q1" value=""/>
<input type="radio" name="q1" value=""/>
<input type="radio" name="q1" value=""/></div>
<div>Q2:...
<input type="radio" name="q2" value=""/>
<input type="radio" name="q2" value=""/></div>
<div>Q3:...
<input type="radio" name="q3" value=""/>
<input type="radio" name="q3" value=""/>
<input type="radio" name="q3" value=""/></div>
<div>Q4:...
<input type="radio" name="q4" value=""/>
<input type="radio" name="q4" value=""/>
<input type="radio" name="q4" value=""/>
<input type="radio" name="q4" value=""/></div>
<input type="submit"/>
</form>
</body>
</html>
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
https://www.experts-exchange.com/questions/22955019/multiple-radio-button-validation-with-a-checkbox-in-between.html
https://www.experts-exchange.com/questions/23770941/Javascript-to-Validate-Radio-Buttons.html
http://www.felgall.com/javatip2.htm