-3

Having problems figuring out a code for my calculator. I have used my textbook for help but still at a loss on why it doesn't calculate at all, just some tips would be awesome.

<html>
<head>
<title> Total Calculator </title>
</head>
<body>
<p>
Bananas:   <input type="text" id="bananasBox" value=""> at $ 0.50 a piece<br>
Sodas  :   <input type="text" id="sodasBox"   value=""> at $ 0.75 per can<br>
Chips  :   <input type="text" id="chipsBox"   value=""> at $1.25 per bag<br>
Candy  :   <input type="text" id="candyBox"   value=""> at $1.00 per pack<br>
TAX is 10 %
</p>
<input type="button" value="Calculate"
<button id='Calculate' onclick= "Calculate()" value="Calculate">Calculate</button>
<script type="text/javascript">


function Calculate() {
    var total = 0;
    var cost = document.getElementById("cost").value;
    var tax = document.getElementById("tax").value;

    total = cost*tax;
    document.getElementById("total").value = total;

document.getElementById('outputDiv').innerHTML= 'Your TOTAL is: ' + total;">
}
</script>
<hr>
<div id="outputDiv"></div>
</body>
</html>
4
  • Change the quotes of 'Calculate Total'()
    – coolguy
    Oct 16, 2012 at 8:23
  • 1
    Where's the closing </script> tag? Why are the quotes around the function name? And I just notice that you seem to have the whole block inside the onlick value... I really recommend to get back to some JavaScript tutorial: w3.org/wiki/Your_first_look_at_JavaScript, w3.org/wiki/Programming_-_the_real_basics, w3.org/wiki/Handling_events_with_JavaScript Oct 16, 2012 at 8:25
  • user means you should remove the quotes and no spaces should be in a methodName Oct 16, 2012 at 8:25
  • Fix your JavaScript in the proper way and call it is function at the onclick properly, from what I am looking at you open <script> but never closes it, you never called the calculate function on the onclick, youre mixing javascript with html without proper usage.
    – Guapo
    Oct 16, 2012 at 8:26

2 Answers 2

1

You have a number of problems.


The HTML is invalid (the button tag stops half way through the onclick attribute).

The end tag for the <script> is missing.


The syntax of a function declaration in JavaScript is:

function identifier() { }

where identifier is the name of the function. Identifiers are not quoted and cannot have spaces in them.


There is no attempt to call your function anywhere in the code.


You make four calls to document.getElementById, but only one of the ids you are trying to access exists.


You end the function with } before the last call to document.getElementById in it.

1
  • went ahead and edited it @Quentin Oct 16, 2012 at 8:46
0

well if you had exactly followed your textbook then i dont think you would face these issues.

  1. function name with a space
  2. verify your input button syntax

2.1 onclick

2.2 close the tag

3 close the script tag

Not the answer you're looking for? Browse other questions tagged or ask your own question.