I am validating two controls from a single onclick. Both controls are mandatory.
Onclick calls the validateLocation function, which, if valid, then calls the validateForm function.
My problem:
If the user selects a state and clicks submit, the Javascript works as expected, perfect.
BUT
If the user selects a seminar location but no state, the javascript will fire, but the selection already made for the location will be cleared. I need that selection to stay selected, so users don’t have to repeat clicks.
My Question:
How to I retain the values if only one of the two criteria are met?
Code below:
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untitled Document</title>
<script type ="text/javascript" language="javascript">
<!--
function validateLocation() {
var radios = document.getElementsByName('RadioGroup1')
for (var i = 0; i < radios.length; i++) {
if (radios[i].checked) {
validateForm();
return true;
}
};
// not checked, show error
document.getElementById('ValidationError').innerHTML = 'Required';
alert("Please select a seminar location");
return false;
}
function validateForm() {
if(document.form1.State.selectedIndex==0)
{
alert("Please select a State");
document.form1.State.focus();
return false;
}
return true;
};
-->
</script>
</head>
<body>
<div>
<form name="form1" onSubmit="return validateLocation();">
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td style="text-align:right">state: </td>
<td>
<select name="State" id="State">
<option value="">Select</option>
<option value="AK">AK</option>
<option value="AL">AL</option>
<option value="AR">AR</option>
</select>
</td>
</tr>
</table>
</div>
<div>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td colspan="2"><strong>Choose a seminar location</strong></td>
</tr>
<tr>
<td valign="top">
<input type="radio" name="RadioGroup1" value="Fayetteville Senior Center" id="RadioGroup1_0">
</td>
<td><strong>Location One</strong></td>
</tr>
<tr>
<td valign="top">
<input type="radio" name="RadioGroup1" value="Springdale Holiday Inn" id="RadioGroup1_1">
</td>
<td><strong>Location Two</strong></td>
</tr>
<tr>
<td valign="top">
<input type="radio" name="RadioGroup1" value="The Riordan Hall" id="RadioGroup1_2">
</td>
<td><strong>Location Three</strong></td>
</tr>
</table>
<div id="ValidationError" name="ValidationError"></div>
</div>
<div>
<input type="submit" name="button" id="button" value="Submit">
</div>
</form>
</div>
</body>
</html>
I’ve slightly changed the script, to get it more logical:
You just need to change the onSubmit handler in the form tag as well to:
Then, the form will be validated, and not submitted, till both validations are successfully.
Hope that helps,
cheers,
Daniel