简体   繁体   中英

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?

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));

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));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM