Jump to content

problem with validation and calculation function


robokopf

Recommended Posts

hi guys, i'm following a tutorial in a Javascript text book that requires me to build a simple Fahrenheit to Celsius converter with a rounded output value and validation. My script contains 2 separate function, validation and calculation and i'm having problems with them. The problem is when i click on the Submit button, without entering values on the fahrenheit text box, the script will pass it as 0 and the result will be displayed on a celsius textbox. and at the same time there's a validation pop-up displaying error message as well. but when i click okay it clears up both the text box. my question is that should i combine and validation and calculation function together using something like a If else statement? thanks in advance.

<html><title> Fahrenheit to Celsius Converter</title><body><script language="Javascript">function Validation(){	if (document.cal.fahrenheit.value.length==0){		window.alert("Please enter in a value...");		document.cal.fahrenheit.value="";		document.cal.celsius.value="";		document.cal.fahrenheit.focus();		return false;	}	else if (isNaN(document.cal.fahrenheit.value)==true){		window.alert("Please enter in a valid value...");		document.cal.fahrenheit.value="";		document.cal.celsius.value="";		document.cal.fahrenheit.focus();		return false;	}	else		return true;}function temp (form){	form.celsius.value = Math.round((form.fahrenheit.value-32)*5/9)}</script><h1>Fahrenheit to Celsius Converter</h1><table><form name=cal action="java script:void()" method=post onsubmit="return Validation();"><tr><td>Fahrenheit:</td><td><input type="text" name="fahrenheit"></td><tr><td><input type="submit" value="Convert it!" onClick="temp (this.form);"></td><td><input type="reset" value="Reset!"></td></tr></tr><tr><td>Celsius:</td><td><input type="text" name="celsius"></td></tr></form></table></body></html>

here's a sample of my code. thanks in advance...

Link to comment
Share on other sites

I think what is happening is that the "temp" function is being called on the click event of the submit button which fires before the submit event of the form.Rather than having "temp" be called from the onclick and "Validation" on submit, you might try creating a third function that is fired on the submit event of the form:

function handleSubmit(){  if(Validation())  {	temp(document.forms["cal"]);  }}

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...