Javascript - decimal format - javascript

Edit: this isn't a math or operators question (I don't think). This is a formatting or masking question.
Creating an order form. I have Javascript that tallies/totals each column and displays the quantity and column cost in two other fields. I would like for the column cost to be formatted with a decimal and 2 values after it, but can't seem to figure it out. .toFixed(2) doesn't seem to work (because it's a string?) and I'm wondering if it's because the quantity and cost fields are readonly?
I'm stuck.
//example of tallying one column
<input type="number" min="0" value="0" name="proA#x#" class="input-mini proA qty1 coffee total">
$(document).on("change", ".qty1", function() {
var sum = 0;
$(".qty1").each(function(){
sum += +$(this).val();
});
$(".total1").val(sum);
$(".cost1").val(sum*9.00);
});
//item tally
<input type="number" id="D1" name="D1" class="input-mini uneditable-input total1" placeholder="0" readonly>
//item cost
<input type="number" id="" name="" class="input-mini uneditable-input cost1" placeholder="x 9.00" readonly >
Thanks in advance!

I would do it this way
var sum = 0.00;
$(".qty1").each(function(){
sum += parseFloat($(this).val());
});
$(".cost1").val(sum.toFixed(2));

Related

how to calculate a number in 2 decimals behind the dot

This is my form:
<input type="text" class="form-control amount" value="" placeholder="amount" />
<input type="hidden" class="price" value="3.30" />
<input type="text" class="form-control total" value="" disabled />
My js:
$('.amount').on('keyup', function (e) {
e.preventDefault();
var amount = $('.amount').val();
var total = Number(amount) * Number($('.price').val());
$('.total').val(total);
});
If i fill in an amount of 3, the result in input with class total shows me: 9.899999999999999 instead of 19.80. (3 * 3.30 is exactly 9.90).
Can someone explain me why the result is so many chars behind the dot?
I know i can reduce the result in 2 decimals with .toFixed(2) but that doesn't explain for me why a value which is exactly 9.90 changes into 9.899999999999999
Fiddle
This is because the way float numbers are stored as binary digits. To enable a wide rage of numbers and still maintain a reasonable size in memory for each number, the precision of results is sacrificed a bit. You can read more about here https://stackoverflow.com/a/588014/3807365
This happens due to the how floating point arithmetic works. In a few words, the floating number is not represented internally as-is, so when the language goes back and forth to display it, there can be some precision issues (such as the one you are facing). See the link for more details.
In summary, as you seem to be handling currency calculations, your best option is to use, instead of float, a specific datatype such as currency.js:
$('.amount').on('keyup', function (e) {
e.preventDefault();
var amount = $('.amount').val();
var total = currency(amount).multiply(currency($('.price').val()));
$('.total').val(total);
});
<script src="https://cdn.jsdelivr.net/npm/currency.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="form-control amount" value="" placeholder="amount" />
<input type="hidden" class="price" value="3.30" />
<input type="text" class="form-control total" value="" disabled />
There are many libs for that, another one is dinero.js.

Not getting total value of input tags

Why my codes is not getting the total value of each row?, its getting only the first row value.
tried to insert it into .each function, but its not functioning
function calc_total()
{
total=0;
$('#po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
}
get the grand total of each rows.
You need to select your inputs differently so you can add their total. Id's must be unique so it won't let you .each a single element. If you give them each a class with the same name you can do it like this:
var total = 0;
$('.po_total_amount').each(function() {
total += parseInt($(this).val());
});
$('#totalPrice').val(total.toFixed(2));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="2">
<input type="input" class="po_total_amount" value="4">
<input type="input" class="po_total_amount" value="90">
<input type="input" id="totalPrice">

Third box locked value JS

I am using an javascript function script in html to get the product of two input boxes into third.
HTML:-
<input type="text" class="form-control" id="inputBuyPrice" placeholder="0.0" name="price" oninput="calculate()">
<input type="text" class="form-control" id="inputBuyAmount" placeholder="0.0" name="amount" oninput="calculate()">
<input type="text" class="form-control" id="inputBuyTotal" placeholder="0.0" name="total" oninput="calculate()">
And the javascript:-
<script>
function calculate() {
var myBox1 = document.getElementById('inputBuyAmount').value;
var myBox2 = document.getElementById('inputBuyPrice').value;
var result = document.getElementById('inputBuyTotal');
var numb = myBox1 * myBox2;
numb = numb.toFixed(8);
result.value = numb;
}
</script>
Now everything is working fine. But value of total gets locked by product of amount and price. I don't want it to be readonly but input that's value can be changed by user.
In a comment you've said:
Simple thing amount*price to be shown in total, but total can be changed manually and incase again price or amount change , product should be shown in total
If that's what you want, just remove the oninput="calculate()" on inputBuyTotal. That will allow the user to change it however they want, but then changing inputBuyPrice or inputBuyAmount will replace what they changed it to with the product of those fields.
(I wish the shops I buy from let me manually change the total amount to pay... πŸ˜‰)
Change
oninput="calculate()"
to
oninput="calculateAmount()"
and add function calculateAmount()

Finding the value of multiple input boxes

I'm building a multiple quantity selector for my store. Image below:
On the site, the price of the product updates based on the quantity added. 10 products = 10% off etc. I'd like to be able to display this price change as and when the user edits any one of the input boxes in the quantity selector.
The input fields are built like this:
<div data-value="S" data-varientid="8195426353207" class="swatch-element swatch-element-2 size s available">
<input id="swatch-0-s" data-variant-id="variant_8195426353207" type="checkbox" name="option-0" value="S">
<label for="swatch-0-s">
S
<img class="crossed-out" src="//cdn.shopify.com/s/files/1/0020/2188/3959/t/2/assets/soldout.png?5180939831627851747" alt="">
</label>
<input id="qty" name="quantity" class="swatchinput" placeholder="0" value="0" type="text">
</div>
I'm able to watch the input boxes for change by doing the below:
var qty = $('.swatchinput');
$('.swatchinput').on('paste keyup', function() {
console.log(qty);
});
However, this returns the information about the element rather than the contents. I'm also unsure of the best way to then add the contents of the various input fields together to reach the total quantity.
You could also use the Array reduce method to do this. Select all the inputs, get the array, then reduce their values into the sum.
var total = $('.swatchinput').get().reduce(function(total, input){
return total + parseInt(input.value || '0');
}, 0);
console.log(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input name="quantity" class="swatchinput" placeholder="0" value="1" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="2" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="3" type="text">
<input name="quantity" class="swatchinput" placeholder="0" value="4" type="text">
This needs to be
var qty = $('.swatchinput').val();
not
var qty = $('.swatchinput');
As for your second question,
loop each of these inputs, getting the value, then add them up with a total. Initialize the total OUTSIDE of the loop also so it doesn't overwrite it.
Something like this?
var total = 0;
$('.switchinput').each(function(){
total += $(this).val();
});
console.log(total);
To get the value of an element in jQuery, use .val():
http://api.jquery.com/val/
.each loops through each matched element and runs a function on that element (accessible through 'this')
http://api.jquery.com/each/

calculating the sum of the array form with javascript

I want to display the number of values ​​in array form. I have a lot of form with only one name is "price []" and have each value on the form. I want to calculate the total value of the form "price []". I'm still a beginner in javascript. and I want to calculate it by using javascript. The following coding that I have made.
<html>
<body>
<form id="hitung" name="hitung">
price 1 <input type="text" name="price[]" class="price" value="1000"/><br>
price 2 <input type="text" name="price[]" class="price" value="3000"/><br>
price 3 <input type="text" name="price[]" class="price" value="2000"/><br>
price 4 <input type="text" name="price[]" class="price" value="1000"/><br>
price 5 <input type="text" name="price[]" class="price" value="3000"/><br><br>
total <input type="text" name="total" class="total"/>
</form>
</body>
</html>
and I want to ask you again, if there is a new input from the outside, then the total will also be changed directly. how to do it. help me please. thank you
Here's an example: http://jsfiddle.net/c4UyA/1/
var sum = 0;
$("form > input[name='price[]']").each(function() {
$this = $(this);
sum += parseInt($this.attr("value"));
});
$("form > input[name='total']").attr("value", sum);

Categories

Resources