Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

function isnumeric : to submit or not submit form?

Status
Not open for further replies.

mwpclark

Programmer
Mar 14, 2005
59
US
Hello

I am using a form to search by zip code. If the visitor does not enter a 5-digit zip code, an alert is generated. So far, so good. Search works, alert works.

However if it returns false, when the OK is clicked on the alert, the form submits anyway. I am seeking a method that will return to the referring page if the zip code entry is not valid, rather than submitting the form.

in <head> :
Code:
<script language="javascript" type="text/javascript">
	function isNumeric(elem, helperMsg){
	var numericExpression = /^\d{5}$/;
	if(elem.value.match(numericExpression)){
		return true;
	}
	else{
		alert(helperMsg);
		elem.focus();
		return false;
	}
}
</script>

in <body>
Code:
<input type="submit" value="GO!" style="font-weight:bold;" onclick="isNumeric(document.getElementById('numbers'), '5-digit Zip Code Please!')">

I have tried <input type="button", which does not submit the form at all. I have tried putting the onclick routine into the <form> tag as an "onSubmit", same results, submits the form when false.

I have tried reversing the true and false elements in the first <script>
Code:
	if(!(elem.value.match(numericExpression))){
		alert(helperMsg);
		elem.focus();
		return false;
	}
	else{
		return true;
	}
Submits form, generates alert, but submits form when click OK on alert. Still no joy.

Any suggestions much appreciated....

One example on
Thanks in advance...

Cheers
Mike
 
Basically you need to return the value from the onclick event or from the onsubmit event.

In other words add a return to your function call:

Code:
<input type="submit" value="GO!" style="font-weight:bold;" onclick="[red][b]return[/b][/red] isNumeric(document.getElementById('numbers'), '5-digit Zip Code Please!')">

If your function returns a false value the onClick will return that value as well and cancel the action.

----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Behind the Web, Tips and Tricks for Web Development.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top