Javascript const variable is changing after multiplying with another variable - javascript

I am trying to create a shopping cart in JavaScript. When I click on the button, the price of item should increase according to the number of times I have clicked on the button. I've tried the below code but it's not working. The problem is that after clicking few times the multiplication goes like this:
suppose initial price =49
49 x 1
49 x 2
94 x 3
282 x 4 (it should be 49 x 4);
I have modified the code,it works fine in console.log() but gives different result if I assign the variable newPrice to document.getElementById().innerHTML
let counter=0;
document.getElementById("inc").addEventListener("click",
function(){
counter++;
const price =document.getElementById("discount").innerHTML;
const newPrice = counter * price ;
const finalPrice = newPrice;
document.getElementById("discount").innerHTML=finalPrice;
})
<b class="mb-1" >price:$<span id="discount">49.20</span></b>
<button type="button" class="roundbutton" id="inc">+</button>

Like was mentioned in the comments, your code included in the question is performing as expected. You are updating the value of document.getElementById("discount").innerHTML. You need to store your price / unit somewhere.
Included is a snippet that demonstrates it.
let counter = 1
const unitPrice = 49.20
document.getElementById("inc").addEventListener("click",function() {
counter++
const price = document.getElementById("discount")
price.innerHTML = (unitPrice * counter).toFixed(2)
})
<b class="mb-1" >price:$<span id="discount">49.20</span></b>
<button type="button" class="roundbutton" id="inc">+</button>

I think you want to parseFloat before you do your multiplication.
let counter=0;
document.getElementById("inc").addEventListener("click",function(){
counter++
const priceElement = document.getElementById("discount")
const price = parseFloat(priceElement.innerHTML);
const newPrice = (price * counter).toFixed(2);
console.log(newPrice)
// store your newPrice elsewhere or you cant maintain your 49 * counter
// priceElement.innerHTML = newPrice
})
<b class="mb-1" >price:$<span id="discount">49.20</span></b>
<button type="button" class="roundbutton" id="inc">+</button>

I think this
const newprice = document.getElementById("discount").innerHTML *=counter;
should be
const newprice = document.getElementById("discount").innerHTML +=counter;
note the + and not the * before the =counter. the plus is adding the star is multiplying.

Related

Total percentages of three input fields

I'm trying to set 100% in total on three input fields. So the idea is when the user sets 30 in one field, in the other two automatically to split numbers up to 100. So in the second field needs to be 35 and in the third one 35. Also, if any number is changed after that, the other two will be adjusted accordingly.
The number in any of those three fields can't exceed 100. I think you are getting the idea of what I'm trying to achieve.
Here is what I have tried so far (I'm not so experienced in JavaScript, but I know that this is a bad approach):
HTML:
<input class="pp-w-100 pp-range-numbers pp-first-field" type="number" name="pp-age-old-2030">
<input class="pp-w-100 pp-range-numbers pp-second-field" type="number" name="pp-age-old-3040">
<input class="pp-w-100 pp-range-numbers pp-third-field" type="number" name="pp-age-old-4050">
JS:
const firstField = document.querySelector('.pp-first-field');
const secondField = document.querySelector('.pp-second-field');
const thirdField = document.querySelector('.pp-third-field');
const totalPercentage = 100;
firstField.addEventListener('change', () => {
let intValue = parseInt(firstField.value);
if (intValue < totalPercentage) {
let getFirstValue = totalPercentage - intValue;
secondField.value = getFirstValue / 2;
thirdField.value = getFirstValue / 2;
}
});
secondField.addEventListener('change', () => {
let intValue = parseInt(firstField.value) + parseInt(secondField.value);
if (intValue < totalPercentage) {
thirdField.value = totalPercentage - intValue;
}
});
The code above is not working as expected.
Thank you.

Ternary Operator not yielding expected result

In JavaScript: I have a ternary operator being instructed to return a tip percentage of %15 if the bill amount is between $50-300, otherwise being instructed to reuturn a tip percentage of %20. On a bill amount of $275, it is still yielding %20. I have looked at many examples of functioning ternary operators and my code seems to be properly worded and yet the result comes out incorrect every time. In what way am I failing?
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
let bill;
let tip_percentage = bill >= 50 && bill <= 300 ? 0.15 : 0.2;
bill = bill_1;
console.log(`The first table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_2;
console.log(`The second table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
bill = bill_3;
console.log(`The third table's bill came out to $${bill}. After the tip of ${tip_percentage}% (equalling: $${bill * tip_percentage}) was added, the final amount owed is: $${bill * tip_percentage + bill}`);
This is the result being given:
As #Matt said in the comment, tip_percentage is not a function and must be calculated each time you change the bill amount.
Try this:
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
function getTip(bill) {
var tip = (bill >= 50 && bill <= 300) ? 0.15 : 0.2;
return tip;
}
alert(`Bill one's tip: ${getTip(bill_1)}`);
alert(`Bill two's tip: ${getTip(bill_2)}`);
alert(`Bill two's tip: ${getTip(bill_3)}`);
tip_percentage is already calculated.
If you want to make different result values depending on the variable, make them in the form of functions.
const bill_1 = 40;
const bill_2 = 275;
const bill_3 = 430;
const tip_percentage = (bill) => (bill >= 50 && bill <= 300 ? 0.15 : 0.2);
const printTipResult = (bill) => {
console.log(`The third table's bill came out to $${bill}.
After the tip of ${tip_percentage(bill)}%
(equalling: $${bill * tip_percentage(bill)}) was added,
the final amount owed is: $${bill * tip_percentage(bill) + bill}`);
};
printTipResult(bill_1);
printTipResult(bill_2);
printTipResult(bill_3);

onchange event repeats calculation after editing the same field

I have a javascript as below:
function calculateBill(id,price)
{
var t = document.getElementById('total').value;
var qty = document.getElementById('qty_'+id).value;
var total = qty * price;
var tcost = Number(t) + Number(total);
document.getElementById('total').value = '';
//tcost = parseFloat(tcost);
document.getElementById('total').value = tcost.toFixed( 0 ) ;
}
This function is called in a onchange event
<input type="text" id = "qty_<?php echo $i2; ?>" name="qty_<?php echo $i2; ?>" onchange="calculateBill('<?php echo $i2; ?>','<?php echo round($r2[$i2]['ret_price'],2); ?>')" />
Since its an onchange event, it calculates the total cost whenever I change the value.
Now my problem is when I want to update the previously entered value, it calculates the new amount to old total.
( Suppose previous value for quantity is 2 , rate is 5 so total
5 * 2 = 10
Hence total is 10 from javascript function
Now if I edit the quanity to 1, insted of 5*1 = 5, I will get 10 + ( 5 * 1) = 15 !
)
How can I prevent this?
Use hidden value for old total like
<input type="hidden" id="old_total" value="<?=$total?>">
Just for the calculation use id old_total
var t = document.getElementById('old_total').value;
And to display output use id total
document.getElementById('total').value = tcost.toFixed( 0 ) ;
Have a hidden field
<input type="hidden" id="hidden_total"/>
Make Hidden field value to have the initial total value when the form loaded.
now, inside the function, use the hidden_total value to add and set it to 0 once you are done with computing.
function calculateBill(id,price)
{
var t = document.getElementById('hidden_total').value;
var qty = document.getElementById('qty_'+id).value;
var total = qty * price;
var tcost = Number(t) + Number(total);
document.getElementById('total').value = tcost.toFixed( 0 ) ;
}
You might need to update the reset the value of hidden field once you have computed, depending on your need. In that case, add the following in the last line;
document.getElementById('hidden_total').value = '';

OnSave Javascript for CRM 2011 quote product

I have an script on the quote product which I want to update the tax value when saving the form. But, it did update the tax according previous values of the fields. The script is as:
function tax ()
{
var val0 = Xrm.Page.getAttribute("baseamount").getValue();
var val1 = Xrm.Page.getAttribute("manualdiscountamount").getValue();
val2 = val0 - val1;
val2 = val2 * 0.05;
Xrm.Page.getAttribute("tax").setValue(val2);
}
For example, if the base amount is 10 and the manual discount is 1 on the create of the quote product, then the tax updates to 0. If after save, I change the base amount to 20 and manual discount is 1, then the tax is updated to 0.45! Mean that, it calculates the tax based on the previous values of the fields!
You are facing this issue because you get the baseamount value before CRM updates it.
baseamout is calculated after the form is saved, so you need to calculate the value by hands as this simplified example:
function tax ()
{
var priceperunit = Xrm.Page.getAttribute("priceperunit").getValue();
var quantity = Xrm.Page.getAttribute("quantity").getValue();
var val0 = priceperunit * quantity;
var val1 = Xrm.Page.getAttribute("manualdiscountamount").getValue();
val2 = val0 - val1;
val2 = val2 * 0.05;
Xrm.Page.getAttribute("tax").setValue(val2);
}
pay attention that there is also the field for volume discount and the product can be also a write-in.

How do I get cart checkout price exact to the penny using Javascript?

How do I get cart checkout price exact to the penny using Javascript?
Right now after taking out all of the trial .rounds etc I was trying.. I am coming up 1.5 cents too high using a high 15 products/prices to test.
for (var i = 0; i < Cookie.products.length; i++) {
boolActive = Cookie.products[i].og_active;
if (boolActive)
{
itemPrice = Cookie.products[i].price;
itemQty = Cookie.products[i].quantity;
itemDiscountPercent = Cookie.products[i].discount_percent;
subtotal = itemPrice * itemQty;
priceDiscount = (subtotal * itemDiscountPercent);
discountAmount += priceDiscount;
}
}
if (!isNaN(discountAmount))
{
var newCartTotal = (cartTotal - priceDiscount);
alert("New Cart Total: " + newCartTotal);
}
var newCartTotal = (cartTotal - pricediscount).toFixed(2)
that will give you the value, but it will be a string. If you need it to stay numeric, use:
var newCartTotal = ((cartTotal - pricediscount * 100) << 0) / 100;
You need to round the discount for each line item: priceDiscount = round_to_hundredth(subtotal * itemDiscountPercent)
Note that this result may not agree with the result you'd get if you add the unrounded results and then round the sum. However, this is the way invoices usually work when calculated by hand (especially since each item can have a different discount percent, so the discount is calculated for each line).
I think you left out a line saying discountAmount += priceDiscount.
modify your code to :
priceDiscount = parseFloat( (subtotal * itemDiscountPercent).toFixed(2) );
and:
newCartTotal = parseFloat( (cartTotal - priceDiscount).toFixed(2) );

Categories