onchange event repeats calculation after editing the same field - javascript

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 = '';

Related

Javascript const variable is changing after multiplying with another variable

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.

Divide input fields with JavaScript

I have 3 input fields:
<input type="text" id ="v0" onkeyup="calculate()"><br>
<input type="text" id ="v1" onkeyup="calculate()"><br>
<input type="text" id="result" onkeyup="calculate()" readonly><br>
What I am trying to do is to count number from 1st input divided by number from 2nd input and displaying it in 3rd input.
function calculate(){
var result = document.getElementById('result');
var el, i = 0, total = 0;
while(el = document.getElementById('v'+(i++)) ) {
el.value = el.value.replace(/\\D/,"");
total = total + Number(el.value);
}
result.value = total;
if(document.getElementById('v0').value =="" && document.getElementById('v1').value ==""){
result.value ="";
}
}
Code is working fine for ADDING this input values, but I need to DIVIDE values from input fields.
I tried to replace "+" with "/" but it breaks the functionality.
You could try a simpler approach like this:
function calculate () {
var input1 = document.querySelector('#v0').value;
var input2 = document.querySelector('#v1').value;
if (input1 && input2) {
document.querySelector('#result').value = (input1 / input2).toFixed(2);
}
}
First of all you have to use "-" for subtraction. But if you want to perform division the problem is that during the first iteration you have total as 0, and it would be:
iteration[1]: 0/anything = 0
iteration[2]: 0/anything = 0
and so on
So you if you want to perform division you need initial value for total, it has to be the 1st input.
Hope that helps.

Javascript Save Max Value of Loop Variable

I have a variable that is updated every 2 seconds with a new value ( speed ) , I want to keep saved the highest value .
How can I do?
snipper
var velocità = spazio / t1; // km/h
console.log('Stai andando a: ' + velocità);
document.getElementById("velocità").innerHTML = velocità;
var max = 0;
...
...
if(velocità > max)
max = velocità;

Calculating a value based on the word count of a textarea using jQuery?

I have the need to calculate a price based on the number of words in a textarea. I will do my best to explain:
Flat fee = $35
Per prompt fee = $10
Per word fee = $.50 (after 30 words)
So I have the following textarea:
<textarea rows="10" class="form-control" name="voice-prompt-1" id="voice-prompt-1" placeholder="Type or paste your prompt here."></textarea>
<p>You have <span class="wordcount">0</span> words.</p>
And the following JS:
var perWord = '.50';
var flatFee = '35.00'
var promptPrice = '10.00';
function wordCount( val ){
return {
words : val.match(/\S+/g).length
}
}
var div = $('span.wordcount');
jQuery('textarea#voice-prompt-1').on('input', function($) {
var count = wordCount( this.value );
div.html(count.words);
additionalFees = perWord*count.words;
total = parseFloat(flatFee) + parseFloat(promptPrice) + parseFloat(additionalFees);
$('span.total').html(parseFloat(total.toString()).toFixed(2));
console.log(total);
});
My question is how do I get the perWord value to calculate only after 30 words is entered?
You want to first check that you have at least 30 words then, subtract 30 form the word count to get additiona fees.
if (count.words > 30) {
additionalFees = perWord * (count.words - 30);
}

How to achieve this Pricing Calculator [duplicate]

This question already has answers here:
Price Calculator based on Quantity [closed]
(4 answers)
Closed 8 years ago.
I am trying to create a simple script to add to a html website.
I need it to calculate the price based on the quantity the user inputs.
For example, a value of 1-1000 will be multiplied by 1.50 and displayed, 1001-5000 multiplied by 1.20 and displayed, 5001-10000 multiplied by 1 and displayed and any number above that would display an error message like "Must be below 10000".
The result is to display in a text field so the user can click submit.
I've been trying to do this in js with no success. If this can be done in any other language please let me know. I'm still learning.
function calc(val) {
if (val < 1 || val > 10000) {
alert("Value must be a positive number under 10,000")
return 0;
}
if (val < 1001) return val*1.5;
if (val < 5001) return val*1.2;
return val;
}
This can be done trough almost every language available for web. Calculating is the most easy thing. For example, in PHP:
$output = $input - 5; // -5
$output = $input + 5; // +5
$output = $input++; // +1
$output = $input * 5; // x5
Javascript plus example:
var input = 5;
var plus = 6;
var output = input+plus;
Javascript min example:
var input = 5;
var plus = 6;
var output = input-plus;

Categories