Matthew,
First, convert your code into a function :
function calc() {
//your statements go here
}
Now add this below the function :
onload = function() {//perform the following statements after the page has loaded
var c = document.getElementById('calculator');//find the "Calculator" button
c.onclick = calc;//run the "calc" function when button is clicked
};
Now add this to the body of the document :
<button id="calculator">Calculator</button>
That should do it.Airshow
Airshow
WiFi Lounge Lizard
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
Matthew,
Ok, so this would be the code?
Nearly. You still have a few things to fix.Delete extra
Convert num1 and num2 from String to Number as follows: var num1 = Number(prompt('Enter your first number',"")); . Same for num2.
In the "add" alert, add missing "+" for string concatenation.
In the "add" alert, protect the mathematical addition with brackets - (num1+num2) - otherwise 6 + 7 will give 67 (string concatenation).
Airshow
Airshow
WiFi Lounge Lizard
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
Oh yes, another thing: "equation" not "equasion".
Airshow
Airshow
WiFi Lounge Lizard
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
Nearly there. Try this:
if (problem=="+")
{
alert("The anwser to your equation is "+(num1+num2)); <--Thats the double braces bit
}
Outer brackets for the alert and inner brackets to ensure mathematical addition of the numbers prior to concatenating the result to the end of the text.
If you still get 6 + 7 = 67, then it's because 6 and 7 haven't been type-converted to Numbers (see my earlier post).
For mathematical operators other than +, type-conversion will be automatic but JavaScript's + is ambiguous; it adds Numbers but concatenates Strings. If one operand is a String and the other a Number, then it treats both as String and concatenates. (Hence your need for the inner brackets).Airshow
Airshow
WiFi Lounge Lizard
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
Matthew, you'd best post your whole code. I'll see what's wrong.
Airshow
Airshow
WiFi Lounge Lizard
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372
Change :
alert("The anwser to your equasion is "(+num1+num2));
to :
alert("The anwser to your equation is "+(num1+num2));
And similarly for the other four calculation lines.
Airshow
Airshow
WiFi Lounge Lizard
2,683 posts since Apr 2009
Reputation Points: 321
Solved Threads: 372