Link to home
Start Free TrialLog in
Avatar of dban00b
dban00b

asked on

Javascript to catch bad form before submit

What code would I need for a javascript function checkform();
That would make sure:
"name" and "color" are not empty ie:  obj.value!=""

If one of them IS empty, then show the div named "warning" and NOT submit the form

However if, they are both populated, then SUBMIT the form


Thanks!
<form id="form1" name="form1" method="post" action="go.php">
 
  <label>Your Name<input type="text" name="name" id="name" /></label>
 
  Your Color:
  <label><input type="radio" name="color" id="color" value="red"  />Red</label>
  <label><input type="radio" name="color" id="color" value="green"  />Green</label>
  <label><input type="radio" name="color" id="color" value="blue"  />Blue</label>
 
  <div id="warning" style="display:none"> Please Complete The Form before submitting</div>
 
    <input type="submit" name="Submit" value="Submit" onclick="checkform(this); return false;" />
 
</form>

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of hielo
hielo
Flag of Wallis and Futuna image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of dban00b
dban00b

ASKER

Not quite right, but pretty darn close, got me what I need, thanks!
<!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 checkForm()
{
		var f=document.getElementById('form1');
        var e="";
        if( f.name.value=="" )
                e+="\nPlease enter your name";
        var c=false;
        for( var i=0; i < f.color.length; ++i)
                if( f.color[i].checked ) c=true;
        if(!c)
                e+="\nPlease Choose a color";
        if(e)
				document.getElementById('warning').style.display='';
		else
			 f.submit();
return e=="";
}
</script>
</head>
<body>
<form id="form1" name="form1" method="post" action="go.php">
 
  <label>Your Name<input type="text" name="name" id="name" /></label>
 
  Your Color:
  <label><input type="radio" name="color" id="color" value="red"  />Red</label>
  <label><input type="radio" name="color" id="color" value="green"  />Green</label>
  <label><input type="radio" name="color" id="color" value="blue"  />Blue</label>
 
  <div id="warning" name="warning" style="display:none;"> Please Complete The Form before submitting</div>
 
    <input type="button" name="Submit" value="Submit" onClick="checkForm(); return false;" />
 
</form> 
</body>
</html>

Open in new window

you are welcome