Javascript Tax Calculator - javascript

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>

Related

Button Becomes Visible after counter reaches threshold

I am trying to make a simple clicker game that you try and generate money through clicking a button. And I want a upgrade button to become visible after you have $10.
Here is the code:
var money = 0
const addMoneyButton = document.getElementById('Clicker')
const addMoney = () => {
money += 1
document.getElementById("money").innerHTML = money
console.log(money)
function upgrade1() {
var upgrade1 = document.getElementById('upgrade1')
if (money > 10) {
upgrade1.style.visibility = 'visible'
}
}
}
addMoneyButton.addEventListener("click", addMoney)
<button id="Clicker">Click To Begin Making Money</button>
<br>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1>
You forgot to call your function:
var money = 0
const addMoneyButton = document.getElementById('Clicker')
const addMoney = () => {
money += 1
document.getElementById("money").innerHTML = money
console.log(money)
function upgrade1() {
var upgrade1 = document.getElementById('upgrade1')
if (money > 10) {
upgrade1.style.visibility = 'visible'
}
}
// here!
upgrade1()
}
addMoneyButton.addEventListener("click", addMoney)
<button id="Clicker">Click To Begin Making Money</button>
<br>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1>
You can shorten your code to this:
const clicker = document.getElementById('Clicker');
const upgrade1 = document.getElementById('upgrade1');
const money = document.getElementById('money');
let count = 0;
clicker.addEventListener('click', () => {
money.textContent = ++count;
if (count > 10) upgrade1.style.visibility = 'visible';
});
<button id="Clicker">Click To Begin Making Money</button>
<button id='upgrade1' style="visibility:hidden;">Upgrade Money Amount</button>
<h1>Money Amount: <span id='money'></span></h1>

How can I save the original value of a data attribute in jQuery

I have an element that I'm using with a quantity input. When the quantity changes I update the data attribute with the new value.
The problem is that when the data attribute is changed, the next iteration of the change is being based off the changed value not the original value.
$(".inc").click(function(){
service = $(this).closest(".service-option-card");
let quantity = getCurrentQuantity(service);
let newQuantity = quantity+1;
setNewQuantity(newQuantity, service);
updatePrice(newQuantity, service);
});
$(".dec").click(function(){
service = $(this).closest(".service-option-card");
let quantity = getCurrentQuantity(service);
let newQuantity = quantity-1;
if(newQuantity <= 0) {
let newQuantity = 0
setNewQuantity(newQuantity, service);
} else {
setNewQuantity(newQuantity, service);
}
updatePrice(newQuantity, $(this).closest(".service-option-card"));
});
function getCurrentQuantity(service) {
let quantity_str = service.find(".quantity").val();
quantity_num = Number(quantity_str);
return quantity_num;
}
function setNewQuantity(quantity, service) {
service.find(".quantity").val(quantity);
}
function updatePrice(quantity, service) {
var price = parseInt(service.find(".price").val().replace(/,/g, ""));
var total = quantity * price;
if(total < 0) {
total = 0;
}
newPrice = numberFormat(total);
service.find(".option-price").html("$" + newPrice);
var monthly = service.data('monthly');
newMonthly = monthly * quantity;
console.log(newMonthly);
updateReceiptMonthly(service, newMonthly);
}
function updateReceiptMonthly(service, newMonthly) {
service.data('monthly', newMonthly);
}
// Number format
function numberFormat(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="service-option-card" data-monthly="10">
<input style="display: none;" class="price" value="50">
<p class="option-price">$50</p>
<div class="quantity">
<button class="btn btn-quantity dec">-</button>
<input class="quantity-input quantity" value="1">
<button class="btn btn-quantity inc">+</button>
</div>
</div>
<div class="col-md-6 services-total-side">
<div class="calculated-totals">
<p class="cost-title">Monthly Cost:</p>
<p class="monthly-cost">$0</p>
</div>
</div>
When you run the above snippet, you can see the console.log is incrementing 10 > 20 > 60 > 240 and so on. this is because when I update the data-monthly attribute on my service-option-card its then multiplying the NEW value by the quantity. What I would like is for it to multiply by the ORIGINAL value of 10 so the console.log should be 10 > 20 > 30 > 40 and so on. I cant just put 10 in because the values change in my application for diffrent service option cards.
You could add another property with the same value, but then keep this value the same. Then you'll always have the original base value to use:
$(".inc").click(function(){
service = $(this).closest(".service-option-card");
let quantity = getCurrentQuantity(service);
let newQuantity = quantity+1;
setNewQuantity(newQuantity, service);
updatePrice(newQuantity, service);
});
$(".dec").click(function(){
service = $(this).closest(".service-option-card");
let quantity = getCurrentQuantity(service);
let newQuantity = quantity-1;
if(newQuantity <= 0) {
let newQuantity = 0
setNewQuantity(newQuantity, service);
} else {
setNewQuantity(newQuantity, service);
}
updatePrice(newQuantity, $(this).closest(".service-option-card"));
});
function getCurrentQuantity(service) {
let quantity_str = service.find(".quantity").val();
quantity_num = Number(quantity_str);
return quantity_num;
}
function setNewQuantity(quantity, service) {
service.find(".quantity").val(quantity);
}
function updatePrice(quantity, service) {
var price = parseInt(service.find(".price").val().replace(/,/g, ""));
var total = quantity * price;
if(total < 0) {
total = 0;
}
newPrice = numberFormat(total);
service.find(".option-price").html("$" + newPrice);
// now using original value here
var monthly = service.data('base-monthly');
newMonthly = monthly * quantity;
console.log(newMonthly);
updateReceiptMonthly(service, newMonthly);
}
function updateReceiptMonthly(service, newMonthly) {
service.data('monthly', newMonthly);
}
// Number format
function numberFormat(nStr)
{
nStr += '';
x = nStr.split('.');
x1 = x[0];
x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="service-option-card" data-monthly="10" data-base-monthly="10">
<input style="display: none;" class="price" value="50">
<p class="option-price">$50</p>
<div class="quantity">
<button class="btn btn-quantity dec">-</button>
<input class="quantity-input quantity" value="1">
<button class="btn btn-quantity inc">+</button>
</div>
</div>
<div class="col-md-6 services-total-side">
<div class="calculated-totals">
<p class="cost-title">Monthly Cost:</p>
<p class="monthly-cost">$0</p>
</div>
</div>

How to find average, maximum, and minimum numbers of a list from user input in HTML

I'm trying to make a code that will evaluate numbers in a list from user input and will calculate the sum, average, minimum, and maximum of that list. I have already gotten the sum part from help from others. I can't seem to find how to get the maximum and minimum numbers from the list. Im trying to have all of the functions (sum, average, max, and min) as buttons just like the sum button that is already in the code and when clicked on it will alert the user of that specific function.
.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- This will list all of the numbers in the list --->
<div class="title">Topics</div>
<ul id='list'></ul>
<!--- When clicked, this will alert the user with the sum of their numbers --->
<button id="something">Click Here To See The Sum</button>
<script>
let list = document.getElementById("list");;
let btn = document.getElementById("something");
let input = document.getElementById("input");
let add = document.getElementById("add");
var sum = 0;
input.addEventListener("input", enableDisable);
btn.addEventListener("click", sumvar);
add.addEventListener("click", function() {
var li = document.createElement("li");
li.textContent = input.value;
sum += +input.value;
list.appendChild(li);
input.value = "";
add.disabled = "disabled";
});
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable(){
if(this.value === ""){
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This function will alert the user of the sum of their numbers
function sumvar() {
alert("The sum of your numbers is: " + sum);
}
</script>
</body>
</html>
You could add the following two functions at the top of your script:
function getNumbersFromList() {
let numbers = [];
for (let i = 0; i < list.children.length; i++) {
numbers.push(parseInt(list.children.item(i).textContent));
}
return numbers;
}
function getStatsForList() {
let numbers = getNumbersFromList();
return {
sum: numbers.reduce((a, v) => a += v),
average: numbers.reduce((a, v) => a += v) / numbers.length,
max: Math.max(...numbers),
min: Math.min(...numbers)
}
}
And then you could use getStatsForList() when you need the updated statistics for your sample.
That function could also easily be modified to add more statistics if needed...
Update
This version only computes the sum once and uses it later to compute the average.
function getStatsForList() {
let numbers = getNumbersFromList();
let sum = numbers.reduce((a, v) => a += v);
return {
sum: sum,
average: sum / numbers.length,
max: Math.max(...numbers),
min: Math.min(...numbers)
}
}
let list = document.getElementById("list");
let input = document.getElementById("input");
let add = document.getElementById("add");
var avg = 0;
var sum = 0;
var min = Infinity;
var max = -Infinity;
// This will add the input number to the list and clear the input
function addClick () {
var li = document.createElement("li");
li.textContent = input.value;
list.appendChild(li);
update();
input.value = "";
add.disabled = "disabled";
}
// This allows the "add to list" button to be turned on/off depending if the user has typed in a number
function enableDisable(){
if(this.value === ""){
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This will calculate and update all variable values
function update() {
sum = 0;
min = Infinity;
max = -Infinity;
var count = 0;
for (var i of list.children) {
let val = +i.textContent;
sum += val;
if (val > max) max = val;
if (val < min) min = val;
count++;
}
avg = sum/count;
}
// This functions will alert the numbers
function sumClick() {
alert("The sum of your numbers is: " + sum);
}
function avgClick() {
alert("The average of your numbers is: " + avg);
}
function minClick() {
alert("The smaller number is: " + min);
}
function maxClick() {
alert("The greater number is: " + max);
}
// Here we add all events
input.addEventListener("input", enableDisable);
add.addEventListener("click", addClick);
document.getElementById("avg").addEventListener("click", avgClick);
document.getElementById("sum").addEventListener("click", sumClick);
document.getElementById("min").addEventListener("click", minClick);
document.getElementById("max").addEventListener("click", maxClick);
.title { font-weight:bold; margin-top:1em; }
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- Here we have a title for the list --->
<div class="title">Topics</div>
<!--- This will list all of the numbers --->
<ul id='list'></ul>
<!--- When clicked, this buttons alert the user with the numbers --->
<button id="sum">Sum</button>
<button id="max">Max</button>
<button id="min">Min</button>
<button id="avg">Avg</button>
You can keep track of the current min, max and count of items, as new items are added compare mins and maxes and calculate the average.
.title { font-weight:bold; margin-top:1em; }
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<!--- This only allows the user to input numbers --->
<input type='number' id='input'>
<!--- This is the button that adds the number to the list --->
<input type='button' value='add to list' id='add' disabled="disabled">
<!--- This will list all of the numbers in the list --->
<div class="title">Topics</div>
<ul id='list'></ul>
<!--- When clicked, this will alert the user with the sum of their numbers --->
<button id="something">Click Here To See The Sum</button>
<script>
let list = document.getElementById("list");;
let btn = document.getElementById("something");
let input = document.getElementById("input");
let add = document.getElementById("add");
var firstLoad = 1;
var sum = 0;
var avg = 0;
var min = 0;
var max = 0;
var count = 0;
input.addEventListener("input", enableDisable);
btn.addEventListener("click", sumvar);
add.addEventListener("click", function()
{
var li = document.createElement("li");
li.textContent = input.value;
sum += +input.value;
count=count+1;
if(firstLoad===1) {
min = input.value; //set min and max first time
max = input.value;
firstLoad = 0; //clear the firstload marker
}
else
{
if(min > input.value) { //compare input to min
min = input.value;
}
if(max < input.value) { //compare input to max
max = input.value; //enteredNumber;
}
}
avg = sum/count; //calculate average
list.appendChild(li);
input.value = "";
add.disabled = "disabled";
});
function enableDisable() {
if(this.value === ""){
add.disabled = "disabled";
} else {
add.removeAttribute("disabled");
}
}
// This function will alert the user of the sum of their numbers
function sumvar() {
alert("sum:" + sum + ",avg:" + avg + ",min:" + min + ",max:" + max);
}
</script>
</body>
</html>

How to calculate total?

I faced a problem for my code and I could not solve it. I have 2 functions, the first one calculates the total and second one discounts the total (if the user write the discount code, it will show the discounted total). But I don't know how to get and call the right value from total to keep it in the second function to calculate the discount because it always shows 0 in the amount. The TOTAL is for the first function and JavaScript code is for the second function.
total = parseInt(TicketsPrice[i].value) * parseInt(NOfTictet);
document.getElementById("total").innerHTML = total;
function discount(coupon) {
var yCoupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var amount;
var input = document.getElementById('discount').value;
if (input == coupon) {
amount = price || 0 * 0.25;
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>
Something like this?
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').value);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * (1 - .25) // 25% off coupon
document.getElementById("Offerprice").innerHTML = amount;
} else {
document.getElementById("Offerprice").innerHTML = 'Invalid coupon'
}
}
<div>Total: <input id="total"></div>
<div>Coupon: <input id="discount"></div>
<button onclick="discount()"> discount</button>
<p><span id ="Offerprice"></span></p>
You have several issues in your code. Here is a working version. I hardcoded the total only for testing because I don't know the HTML for your tickets:
var total = 500; //This is only for testing.
document.getElementById("total").innerHTML = total;
function discount() {
var coupon = "winner1";
var price = Number(document.getElementById('total').innerHTML);
var input = document.getElementById('discount').value;
if (input == coupon) {
var amount = price * 0.75; //discount of 25%
document.getElementById("Offerprice").innerHTML = amount;
} else {
alert("Invalid");
}
}
<input type="text" name="coupon" id="discount">
<button onclick="discount()">discount</button>
<p id="total"></p>
<p><span id="Offerprice"></span></p>

How to properly use variables and Math.round

So i have this javascript that updates a paragraph, but it only outputs NaN. When i check the var coins it outputs ? before i click the button, i and if i push the button in the HTML it adds 0.01 every time i click it, and then my output ends up like this ?0.010.010.010.01.01... Any idea why this happens?
var Cpc = 0.01; //Coins per Click
var coins = 0; //Coins
var cps = 0; //Coins per Sec
setInterval(update, 10);
function update() {
var coinsFix = Number(Math.round(coins + 'e2') + 'e-2');
document.getElementById('Coins').innerHTML = coinsFix + ' $';
document.getElementById('CoinsB').innerHTML = coinsFix;
document.getElementById('Cps').innerHTML = cps + ' Cps';
}
function CPC() {
function cpc() {
var addCoins = coins + Cpc;
return addCoins;
}
coins = cpc();
}
<div class="rightBox">
<div id="ClickSpot">
<button id="clickButton" onClick="CPC()"> <img src="ClickerCoin.png" alt="ClickerSpot" class="ClickerSpot"> </button>
</div>
</div>
<div class="bottomBox">
<p id="Coins">Coins</p>
<div id="CoinsB" style="display: none"></div>
<p id="Cps">Cps</p>
</div>
You could use Number.toFixed with two digits. The result is a string.
The toFixed() method formats a number using fixed-point notation.
var coinsFix = coins.toFixed(2);
// ^^^^^^^^^^^
var Cpc = 0.01; //Coins per Click
var coins = 0; //Coins
var cps = 0; //Coins per Sec
setInterval(update, 10);
function update() {
var coinsFix = coins.toFixed(2);
document.getElementById('Coins').innerHTML = coinsFix + ' $';
document.getElementById('CoinsB').innerHTML = coinsFix;
document.getElementById('Cps').innerHTML = cps + ' Cps';
}
function CPC() {
function cpc() {
var addCoins = coins + Cpc;
return addCoins;
}
coins = cpc();
}
<div class="rightBox">
<div id="ClickSpot">
<button id="clickButton" onClick="CPC()"> <img src="ClickerCoin.png" alt="ClickerSpot" class="ClickerSpot"> </button>
</div>
</div>
<div class="bottomBox">
<p id="Coins">Coins</p>
<div id="CoinsB" style="display: none"></div>
<p id="Cps">Cps</p>
</div>
Change
setInterval(update, 10);
to
setInterval("update()", 10);
also
var coinsFix = Number(Math.round(coins + 'e2') + 'e-2');
to
var coinsFix = coins.toFixed(2);
Try this:
var Cpc = 0.01; //Coins per Click
var coins = 0; //Coins
var cps = 0; //Coins per Sec
setInterval("update()", 10);
function update() {
var coinsFix = coins.toFixed(2);
document.getElementById('Coins').innerHTML = coinsFix + ' $';
document.getElementById('CoinsB').innerHTML = coinsFix;
document.getElementById('Cps').innerHTML = cps + ' Cps';
}
function CPC() {
function cpc() {
var addCoins = coins + Cpc;
return addCoins;
}
coins = cpc();
}
<div class="rightBox">
<div id="ClickSpot">
<button id="clickButton" onClick="CPC()"> <img src="ClickerCoin.png" alt="ClickerSpot" class="ClickerSpot"> </button>
</div>
</div>
<div class="bottomBox">
<p id="Coins">Coins</p>
<div id="CoinsB" style="display: none"></div>
<p id="Cps">Cps</p>enter code here
</div>

Categories

Resources