473,788 Members | 3,030 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Calculator Help

mwh
Hi. If you remember, I posted Expressons Help. Now I am making a
calculator with javascript. I can't get this to work:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<title>Calculat or</title>
<script language="Javas cript">
<!-- Begin Hiding
var total = 0
var operator = 0
function calculate(numbe r){
firm = document.form.v alue1
firm.value = firm.value + number
}
function operator(opvalu e){
theoperator = opvalue
total = document.form.v alue1.value
document.form.s up.value = ""
}
function equals(){
currentDspvalue = eval(document.f orm.value1.valu e)
previousDspvalu e = eval(total)
// add
if (theoperator == "+"){
answer = currentDspvalue + previousDspvalu e
}
// divide
else if (theoperator == "/"){
answer = currentDspvalue / previousDspvalu e
}
// multilply
else if (theoperator == "*"){
answer = currentDspvalue * previousDspvalu e
}
// subtract
else if (theoperator == "-"){
answer = currentDspvalue - previousDspvalu e
}
document.form.s up.value = answer
}
// -->
</script>
<body bgcolor="blue">
<form name="form">
<input name="value1" length=15 type="text"><br >
<input name="1" type="button" value="1" onClick="calcul ate(1)">
<input name="2" type="button" value="2" onClick="calcul ate(2)">
<input name="3" type="button" value="3" onClick="calcul ate(3)">
<input name="4" type="button" value="4" onClick="calcul ate(4)">
<input name="5" type="button" value="5" onClick="calcul ate(5)">
<input name="6" type="button" value="6" onClick="calcul ate(6)">
<input name="7" type="button" value="7" onClick="calcul ate(7)">
<input name="8" type="button" value="8" onClick="calcul ate(8)">
<input name="9" type="button" value="9" onClick="calcul ate(9)">
<input name="0" type="button" value="0" onClick="calcul ate(0)">
<input name="decimal" type="button" value=" . " onClick=calcula te(".")>
<input name="plus" type="button" value="Plus" onClick =operator("+")>
<input name="minus" type="button" value="minus" onClick =operator("-")>
<input name="multiply" type="button" value="times" onClick
=operator("*")>
<input name="divide" type="button" value="divided by" onClick
=operator("/")>
<input name="equals" type="button" value=" = " onClick = "equals()">
<input name="reset" type="reset" value="clear">
</form>
</body>
</html>

It works fine until I press the equal button. Instead of displaying the
answer in the text area, It just says "Error on Page" in the status
bar.

Can Anyone help?
(____)
(\/)
/-------\/
/ | MWH ||
- ||----||

Jul 23 '05 #1
4 1932
mwh wrote:
Hi. If you remember, I posted Expressons Help. Now I am making a
calculator with javascript. I can't get this to work:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<title>Calculat or</title>
<script language="Javas cript">
The language attribute is depreciated, type is required:

<script type="text/javascript">
<!-- Begin Hiding
Completely unnecessary.
var total = 0
You should end statements with a semi-colon, though it isn't strictly
required and isn't causing your issues here.

var total = 0;
var operator = 0
function calculate(numbe r){
firm = document.form.v alue1
firm.value = firm.value + number
}
function operator(opvalu e){
You have a global variable called 'operator' and a function called
'operator'. Firefox assigns 'operator' to the variable, the function
is not defined. Change the name of either the variable or the
function.

Seems you really wanted the global variable to be 'theoperator', so I'd
change the declaration of the variable (and tweak the name) to:

var theOperator = 0

theoperator = opvalue
total = document.form.v alue1.value
document.form.s up.value = ""
There is no element in the form 'form' with a name of 'sup', did you
mean 'value1'?
}
function equals(){
You have defined equals as a form element name, that conflicts with
your equals function name - change one of them (I'll change the
element name since you don't use it for anything anyway).
currentDspvalue = eval(document.f orm.value1.valu e)
Do not use 'eval', there is nearly always a better way. In this case,
it is totally redundant.

currentDspvalue = document.form.v alue1.value;
previousDspvalu e = eval(total)
And here too.

previousDspvalu e = total;

// add
if (theoperator == "+"){
answer = currentDspvalue + previousDspvalu e
The variables you are adding are likely strings, you need to ensure
they are numbers. The unary operator is simplest:

answer = +currentDspvalu e + +previousDspval ue;
}
// divide
else if (theoperator == "/"){
answer = currentDspvalue / previousDspvalu e
}
// multilply
multiply ?

else if (theoperator == "*"){
answer = currentDspvalue * previousDspvalu e
}
// subtract
else if (theoperator == "-"){
answer = currentDspvalue - previousDspvalu e
}
document.form.s up.value = answer
}
It may be suitable to use a switch statement rather than ifs, but
that's up to you.
// -->
Remove this too.
</script>
<body bgcolor="blue">
<form name="form">
Forms require an action attribute, even if it's empty:

<form name="form" action="">

I'd change the name of the form to make it more obvious that it is the
name of a form, not just a form.
<input name="value1" length=15 type="text"><br >
Inputs do not have a 'length' attribute. 'size' will set the width of
a text input in characters, 'maxlength' will set the maximum number of
characters the user may enter.
<input name="1" type="button" value="1" onClick="calcul ate(1)">
<input name="2" type="button" value="2" onClick="calcul ate(2)">
<input name="3" type="button" value="3" onClick="calcul ate(3)">
<input name="4" type="button" value="4" onClick="calcul ate(4)">
<input name="5" type="button" value="5" onClick="calcul ate(5)">
<input name="6" type="button" value="6" onClick="calcul ate(6)">
<input name="7" type="button" value="7" onClick="calcul ate(7)">
<input name="8" type="button" value="8" onClick="calcul ate(8)">
<input name="9" type="button" value="9" onClick="calcul ate(9)">
<input name="0" type="button" value="0" onClick="calcul ate(0)">
<input name="decimal" type="button" value=" . " onClick=calcula te(".")>
You must use quotes around javascript in the onclick attribute:

<input name="decimal" type="button" value=" . "
onClick="calcul ate('.')">

The same goes for all following onclick attributes:
<input name="plus" type="button" value="Plus" onClick =operator("+")>
<input name="minus" type="button" value="minus" onClick =operator("-")>
<input name="multiply" type="button" value="times" onClick
=operator("*")>
<input name="divide" type="button" value="divided by" onClick
=operator("/")>
<input name="equals" type="button" value=" = " onClick = "equals()">
Change the name of this element, say:

<input name="signEqual s" ... >
<input name="reset" type="reset" value="clear">
</form>
</body>
</html>

It works fine until I press the equal button.


I presume you are not using any debugging tools or you would not have
come to that conclusion.

A working version of your script with the above corrections applied is
below.

[...]

The above fixes just get your current code to work, there is a lot more
required before your calculator becomes a robust solution. For
example, you do not prevent users directly entering characters into
the text field and do not validate the input at all.

Once a sum is complete, the first entry of the next number is appended
to the last result - users have to clear the input manually.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<title>Calculat or</title>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<script type="text/javascript">

var total = 0
var theOperator = 0

function calculate(numbe r){
firm = document.form.v alue1;
firm.value = firm.value + number;
}

function operator(opvalu e){
theOperator = opvalue;
total = document.form.v alue1.value;
// document.form.s up.value = ""
document.form.v alue1.value = ""
}

function equals(){
// currentDspvalue = eval(document.f orm.value1.valu e);
currentDspvalue = document.form.v alue1.value;
previousDspvalu e = total;

// add
if (theOperator == "+"){
answer = +currentDspvalu e + +previousDspval ue;
// divide
} else if (theOperator == "/"){
answer = currentDspvalue / previousDspvalu e
// multiply
} else if (theOperator == "*"){
answer = currentDspvalue * previousDspvalu e
// subtract
} else if (theOperator == "-"){
answer = currentDspvalue - previousDspvalu e
}
// document.form.s up.value = answer
document.form.v alue1.value = answer;
}
</script>
<body bgcolor="blue">
<form name="form">
<input name="value1" size="15" type="text"><br >
<input name="1" type="button" value="1" onClick="calcul ate(1)">
<input name="2" type="button" value="2" onClick="calcul ate(2)">
<input name="3" type="button" value="3" onClick="calcul ate(3)">
<input name="4" type="button" value="4" onClick="calcul ate(4)">
<input name="5" type="button" value="5" onClick="calcul ate(5)">
<input name="6" type="button" value="6" onClick="calcul ate(6)">
<input name="7" type="button" value="7" onClick="calcul ate(7)">
<input name="8" type="button" value="8" onClick="calcul ate(8)">
<input name="9" type="button" value="9" onClick="calcul ate(9)">
<input name="0" type="button" value="0" onClick="calcul ate(0)">
<input name="decimal" type="button" value=" . "
onClick="calcul ate('.')">
<input name="plus" type="button" value="Plus"
onClick="operat or('+')">
<input name="minus" type="button" value="minus"
onClick="operat or('-')">
<input name="multiply" type="button" value="times"
onClick="operat or('*')">
<input name="divide" type="button" value="divided by"
onClick="operat or('/')">
<input name="signEqual s" type="button" value=" = "
onClick="equals ()">
<input name="reset" type="reset" value="clear">
</form>
</body>
</html>
--
Rob
Jul 23 '05 #2
JRS: In article <J5************ *****@news.optu s.net.au>, dated Wed, 11
May 2005 02:28:57, seen in news:comp.lang. javascript, RobG
<rg***@iinet.ne t.auau> posted :

Forms require an action attribute, even if it's empty:

<form name="form" action="">
Testers and validators may not like an empty action : I've settled at
present on action="#" .
I'd change the name of the form to make it more obvious that it is the
name of a form, not just a form.


Indeed; I'd suggest that, except for variables local to a short
function, it's generally helpful not to use as an identifier anything
which is reserved or predefined in javascript, or which is likely to
occur in the rest of the page.

Then one may use general file-handling tools such as MiniTrue without
much risk of finding irrelevant occurrences.
ASIDE : most of my pages are now mostly converted to the
better code-displaying functions (Thanks, LRN).

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 MIME. ©
Web <URL:http://www.merlyn.demo n.co.uk/> - FAQish topics, acronyms, & links.
I find MiniTrue useful for viewing/searching/altering files, at a DOS prompt;
free, DOS/Win/UNIX, <URL:http://www.idiotsdelig ht.net/minitrue/> Update hope?
Jul 23 '05 #3
mwh
Thank You!

I am a very novice javascript author, I thank you alot.

(____)
(\/)
/-------\/
/ | MWH ||
- ||----||

Jul 23 '05 #4
mwh
Thank You!

I am a very novice javascript author, I thank you alot.

(____)
(\/)
/-------\/
/ | MWH ||
- ||----||

Jul 23 '05 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
7306
by: Rafael | last post by:
Hi Everyone, I need some help with my calculator program. I need my program to do 2 arguments and a 3rd, but the 3rd with different operators. Any help would be great. Here is my code.... #include <stdio.h> #include <stdlib.h>
2
1460
by: XIII | last post by:
i just created this benefits calculator, but it doesn't work, there is no changes happen after submitting, anyone can help in that?? <html> <head> <title> |||Stocks Calculator||| </title> <style type="text/css"> <!-- body {font-size: 14pt} ..heading {font-size: 18pt; color: red} -->
3
15143
by: PieMan2004 | last post by:
Hi, ive been looking for a solid java community to help me when im tearing out my hair :) Basically ive constructed a GUI that has to represent the same look and functions of the typical windows calculator. Ive made 4 classes 2 do this, my reasoning so it was easier to look through( when programming) rather than getting mixed up in my own code! My questions and problems: Ive been messing around with the windows look and feel,...
24
6341
by: firstcustomer | last post by:
Hi, Firstly, I know NOTHING about Javascript I'm afraid, so I'm hoping that someone will be able to point me to a ready-made solution to my problem! A friend of mine (honest!) is wanting to have on his site, a Javascript Calculator for working out the cost of what they want, for example: 1 widget and 2 widglets = £5.00
19
4033
by: TexasNewbie | last post by:
This was originally just a calculator without a decimal point. After I added the decimal, it now tells me invalid second number. //GUI Calculator Program import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.io.*;
1
2942
by: Synapse | last post by:
Hello... We were asked to create a simple calculator program in our C++ subject by using loops only. i have a problem in creating a loop in the multiplication and division operation so please can anyone help me on this please. and also during the operation selection, if ill enter a character it wont go back to the main program. by the way, my compiler is Dev-C++. I need help badly..here's my code below... #include <iostream.h> #include...
1
5668
by: remya1000 | last post by:
from my system i need to open a calculator in remote machine. and i'm using Vb.net and WMI. i need to pop up the calculator in remote machine, while i run one program in my system. while running in rmotre machine's taskmanager the calculator is displaying, but its not popuping. i tried this code for pop up using Win32_ProcessStartup like this... Module Module1 Sub Main() Dim retValue As String retValue = RunCommand("calc.exe",...
3
11857
by: itsmichelle | last post by:
This is a very primative code of a java swing calculator. I have assigned all the number buttons and the operator buttons and I can add, subtract, multiply, and divide two numbers together. However, my teacher wants the operators to follow the algebraic order of operations by chaining multiple operations. Such as, 7 + 4 * 2= 15. The operatorListener is the ActionListener for the operator buttons. Thanks for any help you can give me. ...
3
2897
by: mandy335 | last post by:
public class Calculator { private long input = 0; // current input private long result = 0; // last input/result private String lastOperator = ""; // keeps track of the last operator entered /* Digit entered as integer value i * Updates the value of input accordingly to (input * 10) + i */
0
9655
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10172
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9964
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8993
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6749
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5398
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
2
3670
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2894
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.