How to do a JavaScript calculation on page load? - javascript

I built a financing calculator, and I have pre-checked values in the HTML. Once is for a 60 month financing term, and the other is for a 10% down payment.
Link to CodeSandbox.
When the page loads up, the calculator hasn't calculated the values yet because in order to do so, the user has to select values and then hit Calculate.
Is there a way for one page load, to load up the total calculated values for the selected values of 60 and 10%?
Thank you in advance!
index.js
// Define product price
const productPrice = 105000;
// Append product price to DOM
const productPriceID = document.getElementById("product-price");
productPriceID.innerHTML = productPrice.toLocaleString();
// Grab the id's of the main product price, down payment, total, per month and button for DOM appending
const downPaymentValue = document.getElementById("down-payment-value");
const totalValue = document.getElementById("total-value");
const perMonthValue = document.getElementById("per-month-value");
const calculateBtn = document.getElementById("calculate");
///////// Calculations
calculateBtn.addEventListener("click", calculate);
function calculate() {
// Grab the value of the month selected
const monthSelected = document.querySelector('input[name="month"]:checked')
.value;
// Grab the value of the down payment percentage selected
const percentageSelected = document.querySelector(
'input[name="percent"]:checked'
).value;
// Calculate down payment percentage based on main price
const totalDownPayment = productPrice * percentageSelected;
// Calculate the total
const totalPrice = productPrice - totalDownPayment;
// Calculate the per month
const perMonth = totalPrice / monthSelected;
// Convert to text with options argument to specify number of decimals
const totalDownPaymentStr = totalDownPayment.toLocaleString(
navigator.language,
{ minimumFractionDigits: 2, maximumFractionDigits: 2 }
);
const totalPriceStr = totalPrice.toLocaleString(navigator.language, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
const perMonthStr = perMonth.toLocaleString(navigator.language, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
});
// Append down payment to DOM
downPaymentValue.innerHTML =
"<sup>$</sup>" + totalDownPaymentStr.toLocaleString();
downPaymentValue.parentNode.appendChild(downPaymentValue);
// Append total to DOM
totalValue.innerHTML = "<sup>$</sup>" + totalPriceStr.toLocaleString();
totalValue.parentNode.appendChild(totalValue);
// Append per month to DOM
perMonthValue.innerHTML = "<sup>$</sup>" + perMonthStr.toLocaleString();
perMonthValue.parentNode.appendChild(perMonthValue);
}
///////// Accessibility
// Grab all labels
const allLabels = document.querySelectorAll("label");
// On enter, select only the ones that are selected
allLabels.forEach(label => label.addEventListener("keyup", onEnter));
function onEnter(e) {
e.preventDefault();
if (e.keyCode === 13) {
this.click();
}
}

You can just call the 'calculate()' function after defining the global variables as 60% and 10% values are pre-checked.
Link to CodeSandbox

Add this line right before calculate function:
window.onload = calculate();

Related

calculating an equation given a certain input from a user with JavaScript

JavaScript newbie here.
I am tasked with calculating a user's monthly payment by using a given equation. I am having trouble with getting the values from the user.
const loanAmount = document.getElementById('loan-amount');
const loanYears = document.getElementById('loan-years');
const loanRate = document.getElementById('loan-Rate');
const span = document.querySelector('span');
const form = document.getElementById("calc-form");
form.addEventListener("submit", function (e) {
e.preventDefault();
console.log('hello')
makeLogo();
});
function makeLogo(loanAmount, loanYears, loanRate) {
const principle = loanAmount.value
const n = loanYears.value * 12;
const i = loanRate.value / 12;
const monthylPayment = (principle* i)/1-(1+ i)** -(n);
span.innerText = monthylPayment;
}
This is what I have so far and am getting an error for the variables in the makeLogo function.
It's a good idea to separate your inputs, calculations and rendering into separate functions. try to keep functions as simple as possible.
You will need to re-evaluate your monthly cost calculator, but here is a working example which takes input, calculates and then renders into form fields.
document.getElementById("calc-form").addEventListener('submit', (e) => {
e.preventDefault();
var loanAmount = document.getElementById('loan-amount').value;
console.log(loanAmount);
var loanYears = document.getElementById('loan-years').value;
var loanRate = document.getElementById('loan-rate').value;
var monthlyPayment = makeLogo( loanAmount, loanYears, loanRate );
console.log(monthlyPayment);
// the monthly has now been calculated, simply put it where you'd like
var calculated = document.getElementById('calculated');
calculated.value = monthlyPayment;
var totalRepayment = document.getElementById('totalRepayment');
totalRepayment.value = monthlyPayment * ( loanYears * 12 );
} );
function makeLogo( principle, loanYears, loanRate) {
var n = loanYears * 12;
var i = loanRate / 12;
var result = ( principle * i) / 1 - ( 1 + i )**-( n );
return result;
}
<html>
<form action='submit' id ='calc-form'>
Loan Amount:<input id ='loan-amount'></input><BR/>
Loan Years:<input id='loan-years'></input><BR/>
Loan Rate:<input id='loan-rate'></input><BR/>
<input type='submit'>
</form>
<span id='span-output'>
Monthly Payment :<input id='calculated' readonly><BR/>
Total Re-Payment :<input id='totalRepayment' readonly>
</span>
</html>
The error you are seeing is likely because the makeLogo function is trying to access the value property of the loanAmount, loanYears, and loanRate variables. Still, they are DOM elements and not their values.
You can fix this by accessing the value property of the DOM elements before passing them to the function like so:
form.addEventListener("submit", function (e) {
e.preventDefault();
console.log('hello')
const principle = loanAmount.value;
const n = loanYears.value * 12;
const i = loanRate.value / 12;
makeLogo(principle, n, i);
});
function makeLogo(principle, n, i) {
const monthylPayment = (principle* i)/1-(1+ i)** -(n);
span.innerText = monthylPayment;
}
This way, the makeLogo function receives the values of the input fields as arguments and can perform the calculation correctly.
Also, make sure that you are getting the right input from the user by checking the value of each element by doing the following:
console.log(loanAmount.value,loanYears.value,loanRate.value)
and check if they are the values that you are expecting.

Input Checkbox Only Updates One Value But Other Inputs Don't Update?

So I have this app I made where it calculates the menu items total and includes a $5 delivery fee. The problem is the 4th option only includes the $5 fee in the total, but the other 3 options don't include the fee
Here's my codepen
https://codepen.io/shodoro/pen/dydNopX
Why is my 4th option, the smoothie $4 the only input checkbox that adds the delivery fee correctly?
The first 3 options don't include the $5 delivery fee in the total and I don't know how to fix it
Here's my JS
function updatePrice() {
let items = 0;
let deliveryFee = document.getElementById('fee')
let tax = document.getElementById('tax')
let tip = document.getElementById('tip')
tax = .1
tip = .2
document.querySelectorAll('input[type=checkbox]').forEach(checkBox => {
if (checkBox.checked) {
items += +checkBox.value
deliveryFee = 5
} else {
deliveryFee = 0
}
})
document.getElementById("price").textContent = `Food Total: $${(items).toFixed(2)}`;
document.getElementById("tax").textContent = `Tax (10%): $${(items * tax).toFixed(2)}`;
document.getElementById("tip").textContent = `Tip (20%): $${(items * tip).toFixed(2)}`;
document.getElementById("total").textContent = `Your order total is: $${((items * tax)+(items * tip)+(items)+(deliveryFee)).toFixed(2)}`;
}
Essential I want all options to include the delivery fee when clicking them, but also making sure the delivery fee resets to 0 whenever you uncheck all options.
That's because you are setting deliveryFee in a loop and so if, for example, the 12 piece wings item is checked, then it sets deliveryFee to 5 and then it's going to loop through to the next item (6 piece wings) and it will set deliveryFee to 0. So when it gets to the calculation for the total, it deliveryFee will be 0 and not 5. I think maybe you want something more like this:
function updatePrice() {
console.log('updatePrice');
let items = 0;
let deliveryFee = 0;
let tax = document.getElementById('tax')
let tip = document.getElementById('tip')
tax = .1
tip = .2
console.log('before forEach loop', items, deliveryFee);
document.querySelectorAll('input[type=checkbox]').forEach(checkBox => {
console.log(checkBox);
if (checkBox.checked) {
console.log('checked!')
items += +checkBox.value
if (deliveryFee == 0) {
console.log('First checked item, setting delivery fee to 5.')
deliveryFee = 5;
}
} else {
console.log('not checked!');
}
})
console.log('after forEach loop', items, deliveryFee);
if (items >= 10) {
deliveryFee = deliveryFee * 2;
}
let orderTotal = (items * tax)+(items * tip)+(items) + deliveryFee;
document.getElementById("price").textContent = `Food Total: $${(items).toFixed(2)}`;
document.getElementById("tax").textContent = `Tax (10%): $${(items * tax).toFixed(2)}`;
document.getElementById("tip").textContent = `Tip (20%): $${(items * tip).toFixed(2)}`;
document.getElementById("fee").textContent = `Delivery Fee: $${deliveryFee.toFixed(2)}`;
document.getElementById("total").textContent = `Your order total is: $${orderTotal}`;
}

Adding a comma to numbers larger than a thousand in JavaScript

I'm building a financing calculator and all of the numbers being outputted to the DOM are in the thousands.
I currently am using .toLocaleString() on one number in my code, and it works (the main productPrice number). I used .toLocatelString() when outputting to the DOM.
However, I can't seem to figure out why when using the same way, it doesn't work on the other numbers. Specifically, the Down Payment, Total and Per Month numbers.
Here's the JS code (the code I've entered .toLocaleString() is at the very bottom):
"use strict";
// Define product price / tax
const productPrice = 105000;
const tax = 0.13;
// Append product price to DOM
const productPriceID = document.getElementById("product-price");
productPriceID.innerHTML = productPrice.toLocaleString();
// Grab the id's of the main product price, down payment, total, per month and button for DOM appending
const downPaymentValue = document.getElementById("down-payment-value");
const totalValue = document.getElementById("total-value");
const perMonthValue = document.getElementById("per-month-value");
const calculateBtn = document.getElementById("calculate");
///////// Calculations
calculateBtn.addEventListener("click", calculate);
function calculate() {
// Grab the value of the month selected
const monthSelected = document.querySelector('input[name="month"]:checked')
.value;
// Grab the value of the down payment percentage selected
const percentageSelected = document.querySelector(
'input[name="percent"]:checked'
).value;
// Calculate down payment percentage based on main price
const totalDownPayment = (productPrice * percentageSelected).toFixed(2);
// Calculate the total
const totalPrice = (productPrice - totalDownPayment).toFixed(2);
// Calculate the per month
const perMonth = (totalPrice / monthSelected).toFixed(2);
// Append down payment to DOM
downPaymentValue.innerHTML =
"<sup>$</sup>" + totalDownPayment.toLocaleString();
downPaymentValue.parentNode.appendChild(downPaymentValue);
// Append total to DOM
totalValue.innerHTML = "<sup>$</sup>" + totalPrice.toLocaleString();
totalValue.parentNode.appendChild(totalValue);
// Append per month to DOM
perMonthValue.innerHTML = "<sup>$</sup>" + perMonth.toLocaleString();
perMonthValue.parentNode.appendChild(perMonthValue);
}
Any idea? Thanks in advance.
It is because your other numbers are being converted to string via toFixed. So toLocaleString does not do anything.
Do all of your math in numbers and convert to strings at the end.
const totalDownPayment = (productPrice * percentageSelected);
const totalPrice = (productPrice - totalDownPayment);
const perMonth = (totalPrice / monthSelected);
convert to text with options argument to specify number of decimals:
const totalDownPaymentStr = totalDownPayment.toLocaleString(navigator.language, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
const totalPriceStr = totalPrice.toLocaleString(navigator.language, { minimumFractionDigits: 2, maximumFractionDigits: 2 })
// ...
See MDN documentation for more information about the options argument.

Keyup: add a value when a checkbox is checked

So I am using Keyup to calculate a total of input fields. So far so good.
But now I want to do this:
if checkbox #a is checked, add 12 to total amount. If not, add 0.
I based my code on this: http://jsfiddle.net/5xzSy/1/
$(document).keyup(function(){ // run anytime the value changes
var element1 = parseFloat($('#element1').val()) * 16.28 || 0; // get value of field and multiply by price
var total = 0+element1
});
How can I add the value of a checked checkbox and substract it if people uncheck it.
(Or even better: with a radiobutton?)
Thank you!
demo: http://jsfiddle.net/5xzSy/1079/ <-- updated (add 12 only if something is given, floatnumber)
btw: input is to be <input/> and not <input></input>
$('input').keyup(function(){ // run anytime the value changes
var firstValue = parseFloat($('#first').val()); // get value of field
var secondValue = parseFloat($('#second').val()); // convert it to a float
var thirdValue = parseFloat($('#third').val());
$('#added').html(firstValue + secondValue + thirdValue); // add them and output it
});
$('#check').on('change', function () {
var total = parseFloat($('#added').text()); // <-- update for float
if (total) {
if ($(this).is(':checked')) {
total = total + 12;
} else {
total = total - 12;
}
$('#added').text(total);
}
})
This should do it...
$(document).keyup(function(){ // run anytime the value changes
var element1 = parseFloat($('#element1').val()) * 16.28 || 0; // get value of field and multiply by price
var total = element1;
if ($('#a').is(':checked')) {
total = total + 12;
}
});

Javascript LocalStorage Setting Other Variables to Null

I have a program that calculates ticket quantities. If I set a new value to a variable using local storage it will cause the other variables to go null. But if I set the value of every variable in the form then nothing will be null and there are no issues, but the problem is I don't want the user to have to set the values of every variable everytime they want to set the value of one variable. How can I rewrite this code so that the other variables won't go to null if one variable is changed? Currently I only have it setup for beforenoonprice and matineeprice, but will add the rest once this issue is resolved.
var beforenoonprice = 6.75; // CHANGE THE PRICE OF THE BEFORE NOON TICKET
var matineeprice = 9.00; // CHANGE THE PRICE OF THE MATINEE TICKET
var seniorprice = 9.25; // CHANGE THE PRICE OF THE SENIOR TICKET
var militaryprice = 9.25; // CHANGE THE PRICE OF THE MILITARY TICKET
var studentdayprice = 8.00; // CHANGE THE PRICE OF THE STUDENT DAY TICKET
var seniordayprice = 6.75; // CHANGE THE PRICE OF THE SENIOR DAY TICKET
var adultprice = 10.75; // CHANGE THE PRICE OF THE ADULT TICKET
var childprice = 8.00; // CHANGE THE PRICE OF THE CHILD TICKET
var threeDprice = 3.50; // CHANGE THE PRICE OF THE REGULAR 3D PRICE
var imaxPrice = 4.50; // CHANGE THE PRICE OF THE IMAX TICKET
var imax3dPrice = 5.50; // CHANGE THE PRICE OF THE IMAX 3D TICKET
var output = document.getElementById('output');
function updatePricingFunction()
{
var beforeNoonFieldChange = document.getElementById('beforeNoonNPSlot').value;
var matineeFieldChange = document.getElementById('matineeNPSlot').value;
localStorage.setItem('text', beforeNoonFieldChange);
localStorage.setItem('text1', matineeFieldChange);
}
function load(){
var storedValue = localStorage.getItem('text');
var storedValue1 = localStorage.getItem('text1');
beforenoonprice = storedValue;
matineeprice = storedValue1;
beforeNoonCPSlot.innerHTML = "$" + parseFloat(storedValue).toFixed(2);
$("#beforeNoonPrice").attr = parseFloat(storedValue).toFixed(2);
$('#beforeNoonPrice').append("$" + (storedValue * 1).toFixed(2));
matineeCPSlot.innerHTML = "$" + parseFloat(storedValue1).toFixed(2);
$("#matineePrice").attr = parseFloat(storedValue1).toFixed(2);
$('#matineePrice').append("$" + (storedValue1 * 1).toFixed(2));
}

Categories

Resources