View Full Version : Checking array of radio buttons
bostjank
11-17-2002, 12:48 AM
Hi!
I have an array of radio buttons (array name is answer). How can I check if a visitor has checked one of them?
If not, I would like to show the alert box, otherwise he could proceed.
I tried return true and return false, but I don't know how to get the value of radio buttons.
Thanks, Bostjan
whammy
11-17-2002, 01:17 AM
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" >
<head>
<title>Radios</title>
<script type="text/javascript">
<!--
function checkanswer(radios){
var checkflag = false;
for(var i=0;i<radios.length;i++){
if(radios[i].checked == true) checkflag = true;
}
if(checkflag == false){
alert('Please choose an answer!');
return false;
}
else{
return true;
}
}
// -->
</script>
</head>
<body>
<form id="blah" action="test.htm" onsubmit="return checkanswer(this.answer)">
<div>
<input type="radio" name="answer" value="1" />1<br />
<input type="radio" name="answer" value="2" />2<br />
<input type="radio" name="answer" value="3" />3<br />
<input type="radio" name="answer" value="4" />4<br />
<input type="radio" name="answer" value="5" />5<br />
<input type="submit" value="Submit" />
</div>
</form>
</body>
</html>
glenngv
11-18-2002, 03:31 AM
you should exit the loop once a radio button is checked.
var checkflag = false;
for(var i=0;i<radios.length;i++){
if(radios[i].checked == true) {
checkflag = true;
break;
}
}
but if you're not fond of using break in a loop, you can do it like this:
var i = 0;
var checkflag = false;
while (i<radios.length && !checkflag){
if (radios[i].checked) checkflag = true;
i++;
}
whammy
11-18-2002, 03:41 AM
Ahh... I knew that was the way to do it, but I wasn't sure of the javascript syntax (and I remember you getting roasted about the same thing, which may be the reason you posted the second option. ;)).
Thanks. :D
glenngv
11-18-2002, 05:53 AM
not really :D
i just found it more fitting to use the 2nd option here (since the boolean flag is needed) than in that thread.
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.