Keyup: add a value when a checkbox is checked - javascript

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

Related

How to do a JavaScript calculation on page load?

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

Why does if statement not work and make my element disappear using display: none?

I am building a tip calculator and I couldn't make the if statement in my function work it just skips to calculating.
function calculate() {
var bill = parseInt(document.getElementById("bill").value);
var tip = parseInt(document.getElementById("tip").value) * .01;
var persons = parseInt(document.getElementById("persons").value);
if (bill == "" || tip == "") {
alert("Please enter value");
return;
};
if (persons == "" || persons <= 1) {
persons = 1;
document.getElementById("perPerson").style.display = "none";
} else {
}
let totalTipPer = (bill * tip) / persons;
let totalPer = (bill + (tip * 100)) / persons;
let totalTip = bill * tip;
let total = bill + (tip * 100);
totalTipPer = totalTipPer.toFixed(2);
totalPer = totalPer.toFixed(2);
total = total.toFixed(2);
totalTip = totalTip.toFixed(2);
document.getElementById("total-tip/person").innerHTML = totalTipPer;
document.getElementById("total-price/person").innerHTML = totalPer;
document.getElementById("total-tip").innerHTML = totalTip;
document.getElementById("total-price").innerHTML = total;
}
document.getElementById("calculate").onclick = function () {
calculate();
document.getElementById('results').style.display = 'block';
}
I expect the div encapsulating Tip Amount per person and total per person and to not appear when the input value of persons is empty.
Function parseInt returns 'An integer number parsed from the given string. If the first character cannot be converted to a number, NaN is returned.'
if you rpovide an empty value ('') it will return
NaN which is not equal to anything, even itself.
there are several ways to fix this:
check if it is a NaN with Number.isNaN(var)
use an intermediate value like var personsValue and check if it is equal to empty string ''.
use Hybrid suggested solution and assign a 0
value for falsy value('', undefined, n
ull etc...)
The issue is that persons becomes NaN, since if the value is left blank, "" becomes NaN when it is run through parseInt().
The way to fix this is by defaulting it to 0 if the field is left blank.
var persons = parseInt(document.getElementById("persons").value || 0);
as others pointed out parseInt is returning NaN if the field is blank, but this will also happen if the user inputs $5.00 for example.
Here's one way to make sure the value can be converted to a number before doing so.
// This function determines if a JavaScript String can be converted into a number
function is_numeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
function calculate() {
// first put the input values into separate variables
billValue = document.getElementById("bill").value;
tipValue = document.getElementById("tip").value;
personsValue = document.getElementById("persons").value;
// use the is_numeric() function above to check if the values can be converted to numeric
if (!is_numeric(billValue) || !is_numeric(tipValue)) {
alert("Please enter values for bill and tip");
return;
}
// the rest of your code here
}
Hope this helps.

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

Check if number exists in a number

I have an odd situation, I think...
I am writing some jquery/javascript code to validate numbers and I need to check if a given int exists within the entered number.
So for instance if the number I am checking against is 15 and the persons types in a 1, I need to check and see if that 1 exists within the 15, if it does then return true else return false.
I tried .stringOf but that of course only works on strings.
Any thoughts? Sorry if it is a super simple answer. Thanks in advance.
So far:
var Quantity = parseFloat(entered_value); // 1
var max = 15;
if(max.indexOf(Quantity) >= 0){
qty = Quantity;
}else{
qty = max;
}
var Quantity = parseFloat(entered_value); // 1
var max = 15;
if(max.toString().indexOf(Quantity.toString()) >= 0){
qty = Quantity;
}else{
qty = max;
}
Just to type out Reason's suggestion
var num = 1,
max = 15,
isSubString = (max+'').indexOf(num) > -1;
if ( isSubString ) {
// Num is a sub string of max
}

multiply two decimals

Im trying to add a tax field. I have this working for whole numbers but i need to be able to enter ".5"
I have no clue haw to solve this problem maybe its because of the isNAN but i thought this would be ok here.
http://jsfiddle.net/thetylercox/eeMva/3/
My current code
$(document).ready(function() {
calculateSum();
$(".txt").keyup(function() {
$(".txt").each(function() {
calculateSum();
});
});
});
$("#tax").keyup(function() {
$('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val()));
);
function calculateSum() {
var sum = 0;
$("#sum").val(sum.toFixed(2));
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#sum").html(sum.toFixed(2));
var subtotal = document.getElementById("subtotal").value == "";
var subtotal = document.getElementById("subtotal").value = sum;
function getTax(tax) {
var taxFloat = parseFloat(tax)
if (isNaN(taxFloat)) {
return 1;
} else {
return taxFloat;
}
}
var total = getTax($('#tax').val()) * sum;
var total1 = document.getElementById("total1").value = total;
} ​
Thanks
Try this:
Put all code including functions inside your $(document).ready(function(){...}) structure.
Perform all calculations, including tax, inside calculateSum().
Use jQuery all through, in particular '$(...)' in preference to .getelementById(...).
Attach calculateSum as the 'keyup' handler for all the user-enterable fields.
Purge all sorts of junk from the code
It should look like this :
$(document).ready(function(){
function getTax() {
var taxFloat = parseFloat($("#tax").val());
return isNaN(taxFloat) ? 1 : taxFloat;
}
function calculateSum() {
var sum = 0;
$(".txt").each(function() {
if (this.value && !isNaN(this.value)) {
sum += parseFloat(this.value);
}
});
$("#subtotal").val(sum.toFixed(2));
$("#total1").val((getTax()*sum).toFixed(2));
}
$(".txt, #tax").keyup(calculateSum);
});
DEMO
You probably want to change the tax algorithm to something more logical. eg. for an entered value of 5(%), the multiplier should be 1.05 .
Taxes are based on percentages. Do the following changes:
$("#tax").keyup(function() {
//$('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val()));
calculateSum();
});
...
function getTax(tax) {
var taxFloat = parseFloat(tax)
if (isNaN(taxFloat)) {
return 1;
} else {
// 1(subtotal) + ?(tax%) -> total = (1 + tax%) * subtotal
return 1 + (taxFloat/100);
}
}
var total = getTax($('#tax').val()) * sum;
// round to 2 decimal digits
total = Math.round(total * Math.pow(10, 2)) / Math.pow(10, 2);
var total1 = document.getElementById("total1").value = total;
So for 5% you enter 5 for 0.5% you enter .5
UPDATE: (Not really an update) As I see more answers coming in, I repeat the logical error for tax field usage. Taxes are percentages worldwide, Meaning that the problem was not only the keyup handling, but also the way tax value was used.
Found your error:
$("#tax").keyup(function() {
$('#total1').val(parseInt($(this).val()) * parseInt($('#subtotal').val()));
});
Here, you parse the tax with parseInt instead of parseFloat, as you do in the function getTax. parseInt(".5") gives NaN. Try to insert values in the .txt inputs after having inserted a tax, and it would work when invoking the calculateSum function.
I can't understand why you would use a different computation when pressing keys in the #tax field than on normal keypresses in other fields. Just use the same listener function, or, if you want to divide the functionality, invoke the function to display the tax both from the #tax keyhandler and the calculateSum function.
Also, there is no need to execute calculateSum() four times when one of the inputs is updated.
See better structured source code in updated fiddle. The maths to calculate taxes and totals was not corrected.

Categories

Resources