Friday 27 September 2013

Simple Calculator calculates wrong

Simple Calculator calculates wrong

Earlier I asked about the same topic, a simple calculator, but the thread
now is kind of cluttered and isn't up-to-date any more. I hope gets
annoyed by this, but I find a new thread kind of useful.
I got an JavaScript exercise to do, which is to script a calculator, which
has almost the same functionality than the built-in Windows (7) one. This
means that you have one field to enter some values, and a small one above
which displays the previously entered value plus the calculating
operation.
A user sent me some code for my needs which I liked because of it's
simplicity and I tried to adapt it.
I currently am working to get only one operation to work, but later there
will be the other three main operations, square root, etc..
Everything works just fine by now, only the, which is kind of disturbing,
calculating itself does not. For example: If you enter 5 + 5 (or any other
number), then click on equals, nothing happens. If you then again enter
any number (click on plus before) and then hit equals it gives you an
completely random result, or the result of your previous calculation.
This is what I got:
var number = 0; //the result
var operation = ' '; //the chosen calculating operation
var temp_Val = 0; //the last entered value (for the
subdisplay)
var print_equal = function () {
var displayVal = document.getElementById("display");
displayVal.value = number;
};
var num_add = function () {
var displayVal = document.getElementById("display");
temp_Val = displayVal.value; //saves the value of the display (for
the subdisplay)
console.log(temp_Val); //schreibt den Wert des Displays auf die
Konsole
number += parseFloat(displayVal.value); //calculates the result
operation = '+'; //saves the used operation (for the
subdisplay)
print_subdisplay(); //runs the function that's building the
value of the subdisplay
displayVal.value = ""; //resets the main display
};
var print_subdisplay = function () {
var subdisplayVal = document.getElementById("subdisplay");
subdisplayVal.value = temp_Val + operation; //creates a String with
both the first entered value and the operation
};
HTML:
<!-- Displays -->
<input type="text" name="display" id="display" value="0"
class="display">
<input type="text" name="subdisplay" id="subdisplay"
class="subdisplay" readonly>
<!-- Calculating operations -->
<input type="button" onclick="print_equal()" id="equal" value="=">
<input type="button" onclick="num_add()" id="plus" value="+">
<!-- Reset -->
<input type="button" value="C" onClick="reset()" class="reset">
Here's the JSFiddle: http://jsfiddle.net/hJfFd/1/
I would find it incredibly nice if you could help me, since I'm sitting
here trying to get this to work since nearly 4 hours (incl. researching).
Thanks in advance!

No comments:

Post a Comment