VashTS
VashTS

Reputation: 27

Print the result of a function in an alert box

So I have a function, lets call it calculate(). This pulls data from some forms, and adds it together if the items are checked or filled in and adds those together.

For the sake of laziness it looks like this

<button onclick=calculate()>Calculate Total</button>
<script type="text/javascript">
function calculate(); {
    var number1 = 2;
    var number2 = 3
var SumAll = number1 + number2;
//print the result in "Sum" paragraph, keep it to two decimals
document.getElementById("Sum").innerHTML = SumAll.toFixed(2);
    }
</script>

What I want to do sounded easy, but I cannot figure it out. I want to print the result in an alert box. Any help for his newb?

Upvotes: 0

Views: 3811

Answers (2)

fbelanger
fbelanger

Reputation: 3578

You're button should look like this.

<button onclick="calculate()">Calculate Total</button>

You also have a semi-colon in the wrong place.

function calculate(); {

And the result is being sent to an element in the DOM with an id of "Sum". To display the var SumAll in an alert box try:

function calculate() {
    var n1 = 2;
    var n2 = 3;
    var sum = n1 + n2;
    alert(sum.toFixed(2));
}

Upvotes: 0

Jeff
Jeff

Reputation: 6953

If you really want a simple alert box:

window.alert(SumAll.toFixed(2));

or

alert(SumAll.toFixed(2));

to print it out in console for debugging:

console.log(SumAll.toFixed(2));

Upvotes: 1

Related Questions