View Full Version : Calcualting values
blackeye
03-15-2009, 01:14 PM
Hello all,
I am in need of some help. I am trying to build a page where a user inputs 2 numbers and then hits a calculate button that displays the input on the screen where the two values are added, subtracted, multiplied and divided. I have no Idea how to get it to display this on a page, all I have is the following:
<FORM onSubmit="docalc()">
First number:
<INPUT TYPE=TEXT name=x><BR>
Second number:
<INPUT TYPE=TEXT name=y><BR>
<INPUT TYPE=BUTTON VALUE="Calculate" onClick="docalc()">
what code do I need to make the page display whatever numbers are put in the two input boxes to be added, subtracted, multiplied and divided shown in one shot?
Help please!!
coothead
03-15-2009, 03:07 PM
Hi there blackeye,
here is an example for you to try...
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<meta http-equiv="Content-Style-Type" content="text/css">
<meta http-equiv="Content-Script-Type" content="text/javascript">
<title>a simple arithmetic calculator</title>
<style type="text/css">
form {
width:248px;
padding:20px;
border:3px double #999;
margin:auto;
background-color:#eee;
}
#numbers label {
width:120px;
margin-bottom:10px;
float:left;
clear:both;
font-size:12px;
}
#numbers input {
width:120px;
margin-bottom:10px;
float:left;
font-size:12px;
}
#buttons {
padding-top:10px;
clear:both;
text-align:center;
}
#buttons input {
font-size:18px;
}
</style>
<script type="text/javascript">
if(window.addEventListener){
window.addEventListener('load',init,false);
}
else {
if(window.attachEvent){
window.attachEvent('onload',init);
}
}
function init() {
count=0;
df=document.forms[0];
df[0].focus();
df[7].onclick=function() {
df[0].focus();
}
inps=document.getElementsByTagName('input');
for(c=0;c<inps.length;c++) {
if(inps[c].type=='button') {
inps[c].number=count++;
inps[c].onclick=function() {
calculate(this.number);
}
}
}
}
function calculate(n) {
x=parseFloat(df[0].value);
y=parseFloat(df[1].value);
if((isNaN(x))||(isNaN(y))) {
alert('numbers only allowed')
df.reset();
df[0].focus();
return;
}
switch(n) {
case 0:
df[2].value=x+y;
break;
case 1:
df[2].value=x-y;
break;
case 2:
df[2].value=x*y;
break;
case 3:
df[2].value=x/y;
break;
}
}
</script>
</head>
<body>
<form action="#">
<div id="numbers">
<label>number one :</label><input type="text">
<label>number two :</label><input type="text">
<label>result :</label><input type="text" readonly="readonly">
</div>
<div id="buttons">
<input type="button" value="+">
<input type="button" value="-">
<input type="button" value="x">
<input type="button" value="÷">
<input type="reset" value="clear">
</div>
</form>
</body>
</html>
vBulletin® v3.6.7, Copyright ©2000-2010, Jelsoft Enterprises Ltd.