Jump to content
xisto Community
Sign in to follow this  
DjLuki

How Do You Make A Javascript Calculator? in a form

Recommended Posts

Hi, does anyone know how you would make a html form with javascript where it calculates number... i will demonstrate below to make it more clear what i mean..i want the form to have like three buttons, MULTIPLY,DIVIDE. AND RESET.. and than i want it to have the fields where you type in the numbers and it gives you the answer.. so its Field 1 * OR / Field 2 = Field 3 . does anyone know how to make this work? i basiaclly want all the three functions to work with the same form. this is a project grade in my web design class but i need help. Thanks

Share this post


Link to post
Share on other sites

With this do you mean you want to create everything from javascript or create a standard form using normal HTML tags and then making use of Javascript to actually compute the values the user enters in. If I am not wrong, you are also trying to integrate an AJAX function into this form too? Since you want to have the fields where you type in the numbers and it gives you the answer. So after a user types in a value, it will compute automatically and display in the results field.

Share this post


Link to post
Share on other sites
<html><head>	<script type="text/javascript">	<!--		function process(task){		var f1 = document.getElementById("field1");		var f2 = document.getElementById("field2");		var ans = document.getElementById("field3");			if(task == "multiply")				ans.value = f1.value * f2.value;			if(task == "divide")				ans.value = f1.value / f2.value;			if(task == "reset"){				ans.value = "";				f1.value = "";				f2.value = "";			}		}	-->	</script></head><body><br />Field 1<input type="text" id="field1" /><br />Field 2<input type="text" id="field2" /><br />Field 3<input type="text" id="field3" /><br /><input type="button" value="Multiply" onclick="process('multiply')" /><input type="button" value="Divide" onclick="process('divide')" /><input type="button" value="Reset" onclick="process('reset')" /></body></html>

I hope that this one will work for you.... that is if i get you correctly..

this kind of calculator will have errors on it.. like what happened if the user will input letters instead of numbers..

you can have a validator that will check if the given field is correct or not..

but the best way is to make 0 - 9 buttons that the user will click... the idea is a calculator like the calculator provided by microsoft...

Share this post


Link to post
Share on other sites

So this is a standard form then. And you are only trying to validate the fields the user enters in?Well you could do the basic validation like checking for empty fields. Make use of the getElementById and use the value field to check for any empty strings submitted by the user. You can also use the isNaN(value) function to check whether it is a number or not. I think ultimately, this is what you are looking at since it is a calculator, it has to deal with numbers and not Strings. So also remember to convert them into integer or whatever depending on your needs. Hope I have helped you :P

Share this post


Link to post
Share on other sites

yeah, i have to put the ELSE functions as well, like when somebody leaves something blank or writes a letter instead of number a message window appear...i am going to try and do this myself, but you can post it here if you know how. it makes my life easier :P

Share this post


Link to post
Share on other sites

Ok here is the whole HTML and Javascript code for a calculator with a validation... its the same code from the one I posted before but I added one function.. isNumber(str) .. which is used to validate the entered string.

 

<html><head>	<script type="text/javascript">	<!--	function isNumber(str){	var index;	var charCode;	var numDash;	var numPeriod;	var numNumeric;		numDash = 0;		numPeriod = 0;		numNumeric = 0;		for(index = 0; index < str.length; index++){			charCode = str.charCodeAt(index);			if(charCode >= 48 && charCode <= 57){				numNumeric++;			}			else if(charCode == 45){				numDash++;				if(numDash > 1) return false;					if(index != 0) return false;			}			else if(charCode == 46){				numPeriod++;				if(numPeriod > 1) return false;			}			else				return false;		}		if(numNumeric == 0) return false;		return true;	}		function process(task){		var f1 = document.getElementById("field1");		var f2 = document.getElementById("field2");	var ans = document.getElementById("field3");		ans.value = "";				if(!isNumber(f1.value) || !isNumber(f2.value))			alert("Invalid field entry!");		else{				if(task == "multiply")						ans.value = f1.value * f2.value;				if(task == "divide")					ans.value = f1.value / f2.value;			if(task == "reset"){						ans.value = "";						f1.value = "";						f2.value = "";					}		}		}	-->	</script></head><body><br />Field 1<input type="text" id="field1" /><br />Field 2<input type="text" id="field2" /><br />Field 3<input type="text" id="field3" /><br /><input type="button" value="Multiply" onclick="process('multiply')" /><input type="button" value="Divide" onclick="process('divide')" /><input type="button" value="Reset" onclick="process('reset')" /></body></html>

Explaination on the validator:

 

First and foremost, the ASCII code for the characters 0 to 9 is 48 to 57, the period * is 46 and the dash (minus sign) is 45. I used the character code in my condition instead of the actual characters becuase its much more easy and straight forward.

 

the variables

 

var numDash;

var numPeriod;

var numNumeric;

 

are used to count how manu dashes, periods and numeric characted in the string. This is useful since the string migt contain more than 1 dash (negative sign) or more than 1 period (floating point) which must not be the case. There is also a need to count the number of numeric characters since the string might contain only a dash (- ) or a period (-). The numNumeric variable is used to check that there must be at least one numeric character in the string.

 

the process of validating the string begins in the for..loop. The loop scans the whole string one character at a time. Every character is checked.

 

If the character is numeric then

the numNumeric variable is incremented by one.

 

if the character is a minus sign (-) then

numDash variable is increment by one

if numDash is greater than 1 which means there is more than 1 dash in the string then

the function exit and return value of false signifying that the given string is not a valid number

if the position of the minus (-) is not in the begining of the string ( at index 0) then

the function exit and return a value of false since the minus sign must of course be in the begining

 

if the character is a period (. ) then

numPeriod varible is inrecmented by one

if numPeriod is greater than 1 meaning more than one decimal piont which is not allowed in a number then

the function exit and return the value of false signifying that the given string is not a valid number

 

if the 3 condition above is not executed then it only means that the character is not a valid character then

the function exit and return the value of false signifying that the given string is not a valid number

 

after the loop finnishes from running the numNumeric is then check if it is greater than 0 becuase if it is not then

the function exit and return the value of false signifying that the given string is not a valid number

 

 

If the condition above evaluated that a character is not valid then the last code

 

return true;

 

which means that the string is a valid number will not be exucted

 

Sorry for the long discussion, its a good way to practice my english :P

Share this post


Link to post
Share on other sites

This is a very long description of your program, but honestly, I am too lazy to go through all that. I would very much like to try out this calculator you have created and who knows maybe there are some bugs which you can solve to make it even better than it is. Is it hosted on any url?

Share this post


Link to post
Share on other sites

With this do you mean you want to create everything from javascript or create a standard form using normal HTML tags and then making use of Javascript to actually compute the values the user enters in.
If I am not wrong, you are also trying to integrate an AJAX function into this form too? Since you want to have the fields where you type in the numbers and it gives you the answer. So after a user types in a value, it will compute automatically and display in the results field.


Actually this program wouldn't need to use AJAX, it shouldn't need to call a script to perform such a simple task. It can all be done in Javascript.

Share this post


Link to post
Share on other sites

hi friendTHis is an excallent calculator written in javascript.....


<FORM NAME="Calc"><TABLE BORDER=4><TR><TD><INPUT TYPE="text" NAME="Input" Size="16"><br></TD></TR><TR><TD><INPUT TYPE="button" NAME="one" VALUE=" 1 " OnClick="Calc.Input.value += '1'"><INPUT TYPE="button" NAME="two" VALUE=" 2 " OnCLick="Calc.Input.value += '2'"><INPUT TYPE="button" NAME="three" VALUE=" 3 " OnClick="Calc.Input.value += '3'"><INPUT TYPE="button" NAME="plus" VALUE=" + " OnClick="Calc.Input.value += ' + '"><br><INPUT TYPE="button" NAME="four" VALUE=" 4 " OnClick="Calc.Input.value += '4'"><INPUT TYPE="button" NAME="five" VALUE=" 5 " OnCLick="Calc.Input.value += '5'"><INPUT TYPE="button" NAME="six" VALUE=" 6 " OnClick="Calc.Input.value += '6'"><INPUT TYPE="button" NAME="minus" VALUE=" - " OnClick="Calc.Input.value += ' - '"><br><INPUT TYPE="button" NAME="seven" VALUE=" 7 " OnClick="Calc.Input.value += '7'"><INPUT TYPE="button" NAME="eight" VALUE=" 8 " OnCLick="Calc.Input.value += '8'"><INPUT TYPE="button" NAME="nine" VALUE=" 9 " OnClick="Calc.Input.value += '9'"><INPUT TYPE="button" NAME="times" VALUE=" x " OnClick="Calc.Input.value += ' * '"><br><INPUT TYPE="button" NAME="clear" VALUE=" c " OnClick="Calc.Input.value = ''"><INPUT TYPE="button" NAME="zero" VALUE=" 0 " OnClick="Calc.Input.value += '0'"><INPUT TYPE="button" NAME="DoIt" VALUE=" = " OnClick="Calc.Input.value = eval(Calc.Input.value)"><INPUT TYPE="button" NAME="div" VALUE=" / " OnClick="Calc.Input.value += ' / '"><br></TD></TR></TABLE></FORM><p align="center"><font face="arial" size="-2">This free script provided by</font><br><font face="arial, helvetica" size="-2">
<a href="https://www.javascriptkit.com/Kit/">Kit</a></font></p>


Edited by OpaQue (see edit history)

Share this post


Link to post
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
Sign in to follow this  

×
×
  • Create New...

Important Information

Terms of Use | Privacy Policy | Guidelines | We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.