...

View Full Version : Radio button validation



Hayes
05-16-2012, 11:15 AM
Hi hope someone here can help me with a problem i'm stuck on. Basically I have 3 radio buttons and one of them has to be selected otherwise display a error message but I cant figure it out.

Here is my failed attempt:

<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript">
function validateForm()
{
var x=document.forms["form1"]["name"].value;
var y=document.form1.difficulty.value;

if (x==null || x=="")
{
alert("First name must be filled out");
return false;
}
if (y==false)
{
alert(y);
return false;
}
}
</script>
</head>
<body>
<div id="horizon">
<div id="content">
<img src="images/logo.jpg" width="649" height="410"></div>
<div id="content2"><form name ="form1" method ="post" action ="game.php" onSubmit="return validateForm()" >

Name: <input type ='text' name='name' />
<br />
<Input type = 'Radio' Name ='difficulty' value= '1' />Easy

<Input type = 'Radio' Name ='difficulty' value= '2' />Medium

<Input type = 'Radio' Name ='difficulty' value= '3' />Hard
<br /><Input type = "Submit" Name = "Submit" VALUE = "Submit">
</form></div></div>
</body>
</html>

Thanks in advance

vwphillips
05-16-2012, 12:23 PM
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style.css" />
<script type="text/javascript">
function validateForm(){
var x=document.forms["form1"]["name"].value;
var y=document.form1.difficulty;
var mess=[];
if (x.replace(/\s/g,'')=="") // remove spaces
{
mess.push("First name must be filled out");
}
mess.push("difficulty must be checked");
for (var z0=0;z0<y.length;z0++){ // the arry of radio buttons
if (y[z0].checked){
mess.length--; // remove "difficulty must be checked"
break;
}
}
if (mess.length>0){
alert(mess.join('\n'));
return false;
}
return true;
}
</script>
</head>
<body>
<div id="horizon">
<div id="content">
<img src="images/logo.jpg" width="649" height="410"></div>
<div id="content2"><form name ="form1" method ="post" action ="game.php" onSubmit="return validateForm()" >

Name: <input type ='text' name='name' />
<br />
<Input type = 'Radio' Name ='difficulty' value= '1' />Easy

<Input type = 'Radio' Name ='difficulty' value= '2' />Medium

<Input type = 'Radio' Name ='difficulty' value= '3' />Hard
<br /><Input type = "Submit" Name = "Submit" VALUE = "Submit">
</form></div></div>
</body>
</html>

Hayes
05-16-2012, 12:34 PM
Exactly what I was after thanks very much :thumbsup:

Philip M
05-16-2012, 01:06 PM
<Input type = 'radio'

Technically, HTML tags are not case sensitive. But in XHTML lower case is required. It's always possible that a future version of HTML may require lower case tags.

Most professionals code tags in lower case and I recommend that others do the same. It may save you a lot of updating at a later time.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum