Link to home
Start Free TrialLog in
Avatar of -Matthew-
-Matthew-

asked on

Form validation - Javascript

My script works part of the time and I don't know why, is there a better way I should be doing this.

<script type="text/javascript" language="javascript">

	function validateForm()
{
var x=document.forms["form1"]["ssn"].value
var y=document.forms["form1"]["NO_ssn"].value
if (x=="" && y=="")
  {
alert("You must type in the last four digits of your Social Security or click the 'No Social Security Number' check box.");
  return false;
  }   
}
</script>

<form  action="somewhere" method="POST" name="form1" id="form1" onsubmit="return validateForm();" >

<input  name="NO_ssn" type="checkbox" id="NO_ssn" value="N/A" />
<input name="ssn" type="text" id="ssn" value="" size="4" maxlength="4" />

</form>

Open in new window

Avatar of Dave Baldwin
Dave Baldwin
Flag of United States of America image

Maybe you're looking at the wrong property:  http://www.w3schools.com/jsref/prop_checkbox_checked.asp
ASKER CERTIFIED SOLUTION
Avatar of experts1
experts1

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 nap0leon
nap0leon

<script type="text/javascript" language="javascript">
function validateForm() {
	var x=document.forms["form1"]["ssn"].value;
	var y=document.forms["form1"]["NO_ssn"].checked;
alert('x='+x);
alert('y='+y);
	if (x=='' && y==false) {
		//user did NOT indicate no SSN and left SSN blank
		alert("You must type in the last four digits of your Social Security or click the 'No Social Security Number' check box.");
		return false;
	} else if (!(x=='') && y==true) {
		//user indicated no SSN but gave one anyway
		alert("You entered the last four digits of your Social Security but clicked the 'No Social Security Number' check box.");
		return false;
	} else if (isNaN(x) && y==false) {
		//user provided an SSN, but it is not a number
		alert("SSNs can only be numbers");
		return false;		
	} else {
		alert('SSN op-out=' + y + '\n' + 'SSN provided=' + x);
		return true;
	}
}
</script>

<form  action="somewhere" method="POST" name="form1" id="form1" onsubmit="return validateForm();" >

No Social Security Number: <input name="NO_ssn" type="checkbox" id="NO_ssn" value="N/A" /><br/>
My last 4 of SSN: <input name="ssn" type="text" id="ssn" value="" size="4" maxlength="4" /><br/>
<input type="submit" value="submit">
</form>

Open in new window