12 Replies - 2012 Views - Last Post: 27 March 2012 - 10:38 PM

#1 StephanieKay90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 25-March 12

JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 10:05 AM

Hey there!

I am almost done with this assignment for class, we are to make a Javascript calculator using checkboxs for the operators and put the calculator in a table. When I run my code the calculations work ok for the most part, but once is start introducing zeros and text mixed with numerics for the operands i get funky answers in the answer box such as infinity. Also, even when the user enters two numerics in the operands, the error stating "you need to enter numerics into the text fields" still pop ups, and sometimes it pops up twice. I need help figuring out which part of my code is causing this errors and what I need to do to fix it.

Also, how do I alter my code so that when the user enters zero in operand B and is trying to divide, it will not do the math and give the user an error?

Instructors Directions:

(See attached image for appearance)

Create a Web page that uses Javascript to create the above application.

Use the document.write ( ) function to put the current date/time on the page as an <H5> which is centered on the page.

The check boxes will determine whether or not the particular math function is performed on the 2 operands. If the box is not checked, the answer box should appear blank.

If either Operand A or B is not numeric data, display an error message using the alert function and do not perform the calculations.

If zero is entered in Operand B, do not divide by zero, display a message, clear the divide checkbox, and put a zero in the answer.

My Calculator Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	
	<head>
	
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	
		<title>Assignment 10: Stephanie Hussar</title>
		
		<script type="text/javascript">
			
			function calculations() {
				var userOpA  = parseInt(validate(document.getElementById('operandA').value));
				var userOpB = parseInt(validate(document.getElementById('operandB').value));

				document.getElementById("answerOutput").value = addition(userOpA, userOpB);
				document.getElementById("answerOutput").value = subtraction(userOpA, userOpB);
				document.getElementById("answerOutput").value = multiplication(userOpA, userOpB);
				document.getElementById("answerOutput").value = division(userOpA, userOpB);
				}


			function validate(value) {
				if (value == null || value == "") {
				alert("Error! Please enter a number in both operand text fields.");
				return 0;
				} else if (isNaN(value)) {
				alert("Error! Please enter numerics only in the operand text fields!");
				return 0;
				}
				else return value;
				}
				
				function addition(userOpA, userOpB){
					return userOpA + userOpB;
					}
			
				function subtraction(userOpA, userOpB){
					return userOpA - userOpB;
					}
					
				function multiplication(userOpA, userOpB){
					return userOpA * userOpB;
				}
				
				function division(userOpA, userOpB){
					return userOpA / userOpB;
				}
				
				
		</script>
	
	</head>
	
	<body>
		
		<script type="text/javascript">
		
		
				var today = new Date();
				document.write("<h1><center> Stephanie's Javascript Calculator </h1></center>");
				document.write("<h5><center>" + today.toLocaleString() +"</h5></center>");

			
		</script>	
			
		
		<form name="Calculator" id="Calculator">
		 
			
			<center>
			<table border="2">
			<tr>
			<td>Operand A</td>
			<td><input id="operandA" type="text" name="operandA" /></td>
			<td>Operand B</td>
			<td><input id="operandB" type="text" name="operandB" /></td>
			</tr>
			<tr>
			<td>Add<input type="checkbox" name="add" id="add" value="Add" onclick="addition()" /></td>
			<td>Subtract<input type="checkbox" name="subtract" id="subtract" value="Subtract" onclick="subtraction()" /></td>
			<td>Multiply<input type="checkbox" name="multiply" id="multiply" value="Multiply" onclick="multiplication()" /></td>
			<td>Divide<input type="checkbox" name="divide" id="divide" value="Divide" onclick="divison()" /></td>
			</tr>
			<tr>
			<td>Answer:<input type="text" id="answerOutput" name="answerOutput" /> </td>
			</tr>
			</table>
			</center>
			
			<br />
			<center>
			<input type="button" id="calculate" name="calculate" value="Calculate" onclick="calculations(); validate()" />
			<input type="reset" id="clear" name="clear" value="Clear" />
			</center>

			
			</form>
		
	</body>
</html>

Attached image(s)

  • Attached Image


Is This A Good Question/Topic? 0
  • +

Replies To: JavaScript Calculator - Why am I getting multiple errors alerts?

#2 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 11:18 AM

there are a couple of problems:
  • incorrect HTML: the 3rd row of the table is incomplete. it should be either a row with four cells or a single cell with the appropriate colspan attribute.
  • document.write(): I have no idea, why your instructor insists on that. it’s completely useless here as you could write the heading in plain HTML.
  • <center> is deprecated. use CSS instead.
  • the onclick-attributes on the checkboxes are counter-productive. these function expect two arguments, but none is given. besides that you already have a "calculate" button. probably the reason you get those weird results.
  • the <form> is missing the required action attribute.
  • calculations() overwrites the output value three times.
  • parseInt() should be given a radix (2nd argument, in your case: 10).
  • what about rational numbers? those would be converted to integers.
  • validate() expects an argument, but none is given in the click handler.
  • an <input>’s value is never null. it is always a string (even if there’s no value, in which case it is the empty string).
  • there is no check for division by Zero.
  • you’re using your XHTML file as HTML file. either keep it as HTML (HTML 4.01 Strict or HTML5) or use XHTML properly (file extension: .xhtml or .xml, MIME-Type: "application/xhtml+xml".


that should be enough for now …

This post has been edited by Dormilich: 27 March 2012 - 11:20 AM

Was This Post Helpful? 0
  • +
  • -

#3 StephanieKay90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 25-March 12

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 12:33 PM

thanks, i changed the table so it is correct, as for the document write and <center> tags i will just leave them for now..

I'm having trouble with these:

the onclick-attributes on the checkboxes are counter-productive. these function expect two arguments, but none is given. besides that you already have a "calculate" button. probably the reason you get those weird results. (so what are you saying here? What two arguments should be given? If i removed the on-click attributes how do i tie the functions to the proper operation and then pass that to the answerOutput text field?)

the <form> is missing the required action attribute.(i'm not looking to store the answers anywhere, so is it necessary to have this in this scenario?)

calculations() overwrites the output value three times.
(I do not understand how to rewrite this then so that one out value will be used for all calculations)
parseInt() should be given a radix (2nd argument, in your case: 10).(I do not know what a radix is nor what you want me to do here.)

validate() expects an argument, but none is given in the click handler.(click handler? what wouldan example of an argument be for the validate function?)

an <input>ís value is never null. it is always a string (even if thereís no value, in which case it is the empty string).(which input value is set to null? do you mean i need a value for every single one?)

there is no check for division by Zero.(do i put an if statement in the divistion function?)

I should probably tell you this is an INTRO course to javascript and we are only though a few chapters! I also have no programmin experience whatsoever! I understand the answers cannot just be given to me and that I need to do my own work but if you could use less techincal lingo in telling me what's wrong with it that would be great! :)
Was This Post Helpful? 0
  • +
  • -

#4 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 01:01 PM

then let me explain in more detail:

Quote

the onclick-attributes on the checkboxes are counter-productive. these function expect two arguments, but none is given. besides that you already have a "calculate" button. probably the reason you get those weird results.

(so what are you saying here? What two arguments should be given? If i removed the on-click attributes how do i tie the functions to the proper operation and then pass that to the answerOutput text field?)

on line #81 - #84 you define the click hanlders (e.g. <input type="checkbox" name="add" id="add" value="Add" onclick="addition()" />). As you can see, there is no argument given. On line #35 you define the function: function addition(userOpA, userOpB){, userOpA & userOpB are the arguments you use to calculate the sum. therefore you need to call the function as (e.g.) addition(1, 2) to work correctly otherwise undefined is passed as argument (and undefined is not a value to calculate with correctly). you are using that function correctly inside the calculations() function.

how to tie that to the output text field: you check what the selected option (that should be a radio button, btw) is (e.g. "addition") and then you perform that particular action. there is a multitude of possibilities, the leaner/shorter, the more advanced. this should be done inside the calculations() function.


Quote

the <form> is missing the required action attribute.

(i'm not looking to store the answers anywhere, so is it necessary to have this in this scenario?)

itís more about principles. HTML defines in its DTD, that every <form> element has to bear an action attribute. whether or not you intent to submit the form does not matter. (btw. XHTML would error out if this attribute were missing). that you can omit it without problems is a browser courtesy.


Quote

calculations() overwrites the output value three times.

(I do not understand how to rewrite this then so that one out value will be used for all calculations)

actually, you only can have one calculation, since you only have one output field. more calculations required more output fields.
essentially, do only the calculation you previously have selected (cf. part 1).


Quote

parseInt() should be given a radix (2nd argument, in your case: 10).

(I do not know what a radix is nor what you want me to do here.)

a radix is the base of the numbering system used. for the decimal system it would be 10, for binary 2, for octal 8 & for hexadecimal 16 (etc.). reason behind is that JS assumes a radix itself, based on the given string (e.g. "010" would be interpreted as octal 10 which is 8 in decimal). for converting decimal strings, you would have to write parseInt(value, 10) to be on the safe side. (parseFloat() always converts to decimal)


Quote

validate() expects an argument, but none is given in the click handler.

(click handler? what wouldan example of an argument be for the validate function?)

same issue as in part 1. line #24 declares the function as function validate(value) {, line #94 calls it as <input type="button" id="calculate" name="calculate" value="Calculate" onclick="calculations(); validate()" /> without argument, lines #14 & #15 call it correctly.


Quote

there is no check for division by Zero.

(do i put an if statement in the divistion function?)

probably the easiest way.


Quote

if you could use less techincal lingo in telling me what's wrong with it that would be great!

I can try, but Iím used to that language because it makes explaining way easier. (ever tried to explain cooking to a kitchen rookie?)
Was This Post Helpful? 1
  • +
  • -

#5 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 01:40 PM

just for the fun of it Ö
Spoiler

Was This Post Helpful? 1
  • +
  • -

#6 StephanieKay90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 25-March 12

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 01:40 PM

Thank you, I hope i didn't come off rude with the lingo thing, I'm just really struggling with this Javascript stuff and my teacher is about as useless as they come, speaking/teaching cryptically (she knows her stuff, but not a very good teacher for beginners)! It's frustrating.. I talk to her after class and am still just as lost as I was before (as is half of the class)

I learn the best by looking at demo code and seeing how the pieces connect, I'm bad with being given written instructions when it comes to coding.. without having some demo code to look at (as I've never worked with JS before this class)

Thanks for the help and taking the time to write all of this! I appreciate it very, very much!
Was This Post Helpful? 0
  • +
  • -

#7 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 01:44 PM

View PostStephanieKay90, on 27 March 2012 - 10:40 PM, said:

I learn the best by looking at demo code and seeing how the pieces connect,

youíre going to "like" the demo code from above then Ö (pretty much every useful concept in JS is covered there)
Was This Post Helpful? 0
  • +
  • -

#8 StephanieKay90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 25-March 12

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 03:12 PM

I know, it would be way easier if we could use buttons, but we have to do it the way she wants (which is always the *** baackwards way)

What would an example of the code be so that the checkboxs do the correct calculation once they are checked and the calculate button is pressed?

do i put the code in the <input type> code..or where do i put that?
Was This Post Helpful? 0
  • +
  • -

#9 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 03:17 PM

View PostStephanieKay90, on 28 March 2012 - 12:12 AM, said:

I know, it would be way easier if we could use buttons,

but you are using a button Ö


View PostStephanieKay90, on 28 March 2012 - 12:12 AM, said:

do i put the code in the <input type> code..or where do i put that?

ideally, you put it in the script itself, which is called Event Handler* or Event Listener**

*
element.onevent = handler_function;

**
element.addEventListener("event", listener_function, bool_useCapture);

Was This Post Helpful? 0
  • +
  • -

#10 StephanieKay90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 25-March 12

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 03:20 PM

oh boy, that's beyond what we're learning in class!

i mean I wish we could use buttons for the operators instead of checkboxs, i know the calculate button is still a button, but i'm so stuck i'm ready to give up!
Was This Post Helpful? 0
  • +
  • -

#11 StephanieKay90  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 17
  • Joined: 25-March 12

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 06:06 PM

I tried re-working it, and now it's STILL NOT WORKING! ugh i've been working at this all day! any ideas?? what am i doing wrong?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
	
	<head>
	
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
	
		<title>Assignment 10: Stephanie Hussar</title>
		
		<script type="text/javascript">
		
				var answer = document.getElementById("answerOutput").value
				var userOpA = document.getElementById('operandA').value
				var userOpB = document.getElementById('operandB').value

			/*
			function calculations() {
				var userOpA = document.getElementById('operandA').value
				var userOpB = document.getElementById('operandB').value

				}
*/

			function validate() {
				if (userOpA == null || userOpB == null) {
				alert("Error! Please enter a number in both operand text fields.");
					return 0;
				} if (isNaN(userOpA) || isNaN(userOpB)) {
				alert("Error! Please enter numerics only in the operand text fields!");
					return 0;
				} if (userOpB = 0 && !document.Calculator.divide.checked){
					alert("Error! You can't divide by zero!")	
				}
				return true;
				}
				
				function addition(userOpA, userOpB){
					answer = userOpA + userOpB;
					return;
					}
			
				function subtraction(userOpA, userOpB){
					answer = userOpA - userOpB;
					return;
					}
					
				function multiplication(userOpA, userOpB){
					answer = userOpA * userOpB;
					return;
				}
				
				function division(userOpA, userOpB){
					answer = userOpA / userOpB;
					return;
				}
				
				
		</script>
	
	</head>
	
	<body>
			
		<script type="text/javascript">	
		
				var today = new Date();
				document.write("<h1><center> Stephanie's Javascript Calculator </h1></center>");
				document.write("<h5><center>" + today.toLocaleString() +"</h5></center>");

			
		</script>	
			
		
		<form name="Calculator" id="Calculator" method="POST">
			
			<center>
			<table width="750" border="2" cellpadding="20">
			<tr>
			<td>Operand A</td>
			<td><input id="operandA" type="text" name="operandA" value="0" /></td>
			<td>Operand B</td>
			<td><input id="operandB" type="text" name="operandB" value="0" /></td>
			</tr>
			<tr>
			<td>Add<input type="checkbox" name="add" id="add" value="Add" onclick="addition()" /></td>
			<td>Subtract<input type="checkbox" name="subtract" id="subtract" value="Subtract" onclick="subtraction()" /></td>
			<td>Multiply<input type="checkbox" name="multiply" id="multiply" value="Multiply" onclick="multiplication()"  /></td>
			<td>Divide<input type="checkbox" name="divide" id="divide" value="Divide" onclick="division()" /></td>
			</tr>
			<tr>
			<td>Answer:</td>
			<td><input type="text" id="answerOutput" name="answerOutput" /> </td>
			<td></td>
			<td></td>
			</tr>
			</table>
			</center>
			
			<br />
			<center>
			<input type="button" id="calculate" name="calculate" value="Calculate" onclick="validate()" />
			<input type="reset" id="clear" name="clear" value="Clear" />
			</center>

			
			</form>
		
	</body>
</html>


Was This Post Helpful? 0
  • +
  • -

#12 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 09:12 PM

for a quick start, check the Error Console.

next thing, make it a group of radio buttons (all having the same name). this will prevent that you can select more than on operation.

more later (when I have more time).
Was This Post Helpful? 0
  • +
  • -

#13 Dormilich  Icon User is offline

  • 痛覚残留
  • member icon

Reputation: 3402
  • View blog
  • Posts: 9,611
  • Joined: 08-June 10

Re: JavaScript Calculator - Why am I getting multiple errors alerts?

Posted 27 March 2012 - 10:38 PM

more to the details.

lines #13 - #15 will give you a "null or not an object" error (you try to access elements before they are created).

line #26, as previously said, userOpA / userOpB are never null.

line #32, there is an assignment instead of a comparison. programmer’s tip: write the condition the other way round: if (0 == my_var) // works if (0 = my_var) // error

the checkboxes should be radio buttons and must not have a click handler (I have previously discussed why).
if you have that group of radio buttons, the only problem is getting the chosen/checked one. for that there is a neat Javascript function called document.querySelector() which parses a CSS Selector expression and returns the first matching element (but since it is a radio button group, there can be only one). from this element you can get the value which is the operation to execute. helpful for that is the CSS pseudo class :checked.

maybe it helps if you imagine the operator choice as dropdown menu (which would be indeed easier …).

and something you probably didn’t have in class yet: userOpA and userOpB should reference the input elements directly (not their values). reason: in JS, objects (which is pretty much everything besides the obvious string/number/boolean literals, null and undefined) are passed/saved as reference (pointer, a location in memory). hence if you save the input element (an object) you can get its actual value by calling its value property. if you save the value directly, you get that at the point of saving (since it is a string literal) which is at page load the empty string ("").

This post has been edited by Dormilich: 27 March 2012 - 10:42 PM

Was This Post Helpful? 0
  • +
  • -

Page 1 of 1