简体   繁体   中英

Javascript Tax Calculator

I'm trying to create a program that sums the three values of the array var prices = [12.3, 20, 30.33]; together, and outputs both the sum and the total bill with tax of 7%.

Here is my HTML:

<p>Sum of numbers in array: <span id="sum"></span></p>

<p>Amount with 7% tax added: <span id="percent"></span></p>

<button onclick="myFunction()">Click Me</button>

JS:

var numbers = [12.3, 20, 30.33];
var taxAmount = .07;

function getSum(total, num) {
    return total + num;
}
function myFunction(item) {
    document.getElementById("sum").innerHTML = numbers.reduce(getSum);
}

function multiply(item) {
    document.getElementById("percent").innerHTML = numbers.reduce(getSum) * .07;
}

What am I doing wrong?

you were not calling the function

 var numbers = [12.3, 20, 30.33]; var taxAmount = .07; function getSum(total, num) { return total + num; } function myFunction(item) { document.getElementById("sum").innerHTML = numbers.reduce(getSum); document.getElementById("percent").innerHTML = numbers.reduce(getSum) * .07; } 
 <p>Sum of numbers in array: <span id="sum"></span></p> <p>Amount with 7% tax added: <span id="percent"></span></p> <button onclick="myFunction()">Click Me</button> 

You don't called the funtion and you need to sum the actual value with the tax of 7%.

numbers.reduce(getSum) + numbers.reduce(getSum) * .07

 var numbers = [12.3, 20, 30.33]; var taxAmount = .07; function getSum(total, num) { return total + num; } function myFunction(item) { document.getElementById("sum").innerHTML = numbers.reduce(getSum); document.getElementById("percent").innerHTML = numbers.reduce(getSum) + numbers.reduce(getSum) * .07; } 
 <p>Sum of numbers in array: <span id="sum"></span></p> <p>Amount with 7% tax added: <span id="percent"></span></p> <button onclick="myFunction()">Click Me</button> 

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