Wrong Output by sum Floatnumber in jQuery / Javascript - javascript

I have a problem. I am trying to sum two float values with jQuery.
<tr id='idList'>
<td class="price" value="2,50">Testsum</td>
<td class="price" value="13,50">Testsum</td>
<td> <input type="text" id="total_price" readonly></td>
</tr>
And my JavaScript:
var sum = 0;
$('.price').each(function(){
sum = $(this).attr('value') + sum;
});
alert(sum);
$('#total_price').val(sum);
I got this output in my text field: 2,5013,50. Why? I cant understand, why doesn't it sum together the two values like: 2,50 + 13,50 = 16,00?

Try using parseInt() function
var sum = 0;
$('.price').each(function(){
sum = parseInt($(this).attr('value')) + sum;
});
alert(sum);
$('#total_price').val(sum);
Check Manual

You are using a string concatenation
var sum = 0;
$('.price').each(function() {
sum += (+$(this).attr('value').replace(',', '.') || 0);
});
$('#total_price').val(sum);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr id='idList'>
<td class="price" value="2,50">Testsum</td>
<td class="price" value="13,50">Testsum</td>
<td>
<input type="text" id="total_price" readonly>
</td>
</tr>
</table>

Related

Calculate values from multiple number fileds - Jquery

I am trying to calculate price based on quantity and price and calculating a subtotal by adding all products prices.
below is the code of html
<tr>
<td>
<input min="0" data-unit-price="9.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<input min="0" data-unit-price="19.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<h3><span class="se-curency">$</span><span data-sub-total="0" id="se-sub-total" class="se-total-amount">0</span></h3>
<h3><span class="se-curency">$</span><span id="se-vat" class="se-total-amount">8</span></h3>
</td>
</tr>
And I am trying The below js
jQuery( document ).on( 'input', '.se-ticket-qty', function() {
var sum = 0;
jQuery(this).each(function(i){
var unit_price = jQuery(this).data('unit-price');
var amount = jQuery(this).val();
var current_sub_total = parseFloat(unit_price);
sum += current_sub_total;
var sub_total = jQuery('#se-sub-total').attr('data-sub-total');
var final_sub_total = parseFloat(sub_total) + sum;
jQuery('#se-sub-total').attr('data-sub-total', final_sub_total.toFixed(2));
jQuery('#se-sub-total').html(final_sub_total.toFixed(2));
});
console.log(sum);
});
But There is an error in calculating.The sub total is working fine if I use upper arrow in number field.But if i use below arrow or input an number by manually it is not working.
It looks like you just had a few small issues with how you were using each logic and adding up the totals. Here is a snippet that does what I think you were trying to do. Just un-comment the console.logs to see how the order of operations changed how the final sum is calculated. I am not sure what you wanted with the second display with 8$:
// Shorthand for $( document ).ready()
$(function() {
console.log( "ready!" );
$(document).on('input', '.se-ticket-qty', function(){
CalculateTotal();
});
});
function CalculateTotal(){
var sum = 0;
$(".tableWithInputs").find( ".se-ticket-qty" ).each(function( index ){
var unit_price = parseFloat($(this).data('unit-price'));
var amount = parseFloat($(this).val());
var totalPrice = unit_price * amount;
//console.log("unit_price: " + unit_price);
//console.log("unit_price: " + unit_price);
//console.log("amount: " + amount);
//console.log("totalPrice: " + totalPrice);
sum += parseFloat(totalPrice);
});
$('#se-sub-total').attr('data-sub-total', sum.toFixed(2));
$('#se-sub-total').text(sum.toFixed(2));
//console.log(sum.toFixed(2));
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tableWithInputs">
<tr>
<td>
<input min="0" data-unit-price="9.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<input min="0" data-unit-price="19.99" class="se-ticket-qty" type="number" value="0" />
</td>
</tr>
<tr>
<td>
<h3><span class="se-curency">$</span><span data-sub-total="0" id="se-sub-total" class="se-total-amount">0</span></h3>
<h3><span class="se-curency">$</span><span id="se-vat" class="se-total-amount">8</span></h3>
</td>
</tr>
</table>

Get values from inputs then add them ,javascript

I am trying to add values from n input field but i get result as NaN
Where am i going wrong
<table>
<tr>
<td><input class="one" name="" value="1" type="text"></td>
<td><input class="two" name="" value="2" type="text"></td>
<td><input class="three" name="" value="3" type="text"></td>
<td><input class="four" name="" value="4" type="text"></td>
<td class="total"> </td>
</tr>
</table>
<script>
var tdsOne = document.getElementsByClassName("one").value;
var tdsTwo = document.getElementsByClassName("two").value;
var tdsThree = document.getElementsByClassName("three").value;
var tdsFour = document.getElementsByClassName("four").value;
var sum = 0;
sum += tdsOne + tdsTwo + tdsThree + tdsFour;
console.log(sum);
document.getElementsByClassName('total')[0].textContent = sum;
</script>
Since document.getElementsByClassName is an array-like object, you need to refer it by it's index
var tdsOne = document.getElementsByClassName("one")[0].value;
var tdsTwo = document.getElementsByClassName("two")[0].value;
var tdsThree = document.getElementsByClassName("three")[0].value;
var tdsFour = document.getElementsByClassName("four")[0].value;
EDIT
If you are looking for arithmetic addition , these values need to be converted to number. You can use Unary plus operator
sum += +tdsOne + +tdsTwo + +tdsThree + +tdsFour;
JSFIDDLE

JavaScript - HTML5 data attributes

I've looked around on the web for an answer to my question. Found lots of scripts that I've copied and messed around with but can't get it working properly.
When I run it, my script below initially works but then displays 'NaN'.
I'm trying to create a simple order form that uses JavaScript to dynamically update and display the order total.
Each item for sale has an input (type=number) tag that contains the item's price in a 'data-price' attribute.
What I'm trying to do is grab the price out of the data-price attribute and use it in a JS script to display a total.
Users can enter a quantity into text field and the TOTAL text field should automatically update with correct 'running total'.
Would appreciate any advice as to where I'm going wrong. I've used JavaScript (as opposed to jQuery) because I'm more familiar with the syntax.
<script>
function calculateTotal(frm) {
var order_total = 0
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i];
item_price = form_field.dataset.pric);
item_quantity = form_field.value;
if (item_quantity >= 0) {
order_total += item_quantity * item_price;
}
}
frm.total.value = round_decimals(order_total, 2);
}
function round_decimals(original_number, decimals) {
var result1 = original_number * Math.pow(10, decimals);
var result2 = Math.round(result1);
var result3 = result2 / Math.pow(10, decimals);
return result3.toFixed(2);
}
</script>
</head>
<body>
<form id="order-form">
<table cellpadding="8" align="center">
<tr>
<td align="left" width="150">Image</td>
<td align="left">Description</td>
<td align="left">Price</td>
<td align="left">Quantity</td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left">Poster</td>
<td align="left">$24.00</td>
<td align="left"><input type="number" data-price="24" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left"> T-shirt</td>
<td align="left">$66.00</td>
<td align="left"><input type="number" data-price="65" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td align="left"><img src="http://placehold.it/150x200"></td>
<td align="left"> Bag</td>
<td align="left">$120.00</td>
<td align="left"><input type="number" data-price="120" min="0" max="50" step="1" value="0" onChange="calculateTotal(this.form)"></td>
</tr>
<tr>
<td></td>
<td></td>
<td>TOTAL:</td>
<td align="right"><input type="text" name="total" size="6" onFocus="this.form.elements[0].focus()"></td>
</tr>
</table>
</form>
</div>
You have a typo in the sample code.
item_price = form_field.dataset.pric);
should probably be
item_price = form_field.dataset.price;
Apart from that, NaN is caused by the fact that you're also taking into account the value of the 'total' field when you run the function calculateTotal(). But that field does not have a data-price attribute so you're multiplying undefined with a number, resulting in NaN.
You need to add an extra check if there is a 'data-price' attribute:
function calculateTotal(frm) {
var order_total = 0;
for (var i=0; i < frm.elements.length; ++i) {
form_field = frm.elements[i];
if(typeof(form_field.dataset.price) != 'undefined') {
item_price = form_field.dataset.price;
item_quantity = form_field.value;
if (item_quantity >= 0) {
order_total += item_quantity * item_price;
}
}
}
frm.total.value = round_decimals(order_total, 2);
}

Sum of all values in a class tag

I want the Grand Total calculation now.. I want the sum of all the values in the Amount field... I tried tis code but its not working...
$(".amt").each(function(){
total=total+(parseInt($(this).val()))
});
According to the following HTML:
<table>
<tr>
<td><input class="amt" /></td>
</tr>
<tr>
<td><input class="amt" /></td>
</tr>
</table>
<div id="total"></div>
The JS would be:
$('table').focusout(function() {
var sum = 0;
$('.amt').each(function(){
if (this.value != "") {
sum += parseFloat(this.value);
}
});
$('#total').html("Grand total: " + sum);
});
JsFiddle
If you are adding these dynamically, you will need to have something like this:
$(document).on('click', '.count', function()
{
var total = 0;
$(".amt").each(function()
{
total=total+(parseInt($(this).val()))
});
alert(total);
});

JavaScript summing of textboxes

I could really your help! I need to sum a dynamic amount of textboxes but my JavaScript knowledge is way to week to accomplish this. Anyone could help me out? I want the function to print the sum in the p-tag named inptSum.
Here's a function and the html code:
function InputSum() {
...
}
<table id="tbl">
<tbody>
<tr>
<td align="right">
<span>June</span>
</td>
<td>
<input name="month_0" type="text" value="0" id="month_0" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>July</span>
</td>
<td>
<input name="month_1" type="text" value="0" id="month_1" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>August</span>
</td>
<td>
<input name="month_2" type="text" value="0" id="month_2" onchange="InputSum()" />
</td>
</tr>
<tr>
<td align="right">
<span>September</span>
</td>
<td>
<input name="month_3" type="text" value="0" id="month_3" onchange="InputSum()" />
</td>
</tr>
</tbody>
</table>
<p id="inputSum"></p>
function InputSum() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {
if(inputs[i].id.indexOf("month_") == 0)
alert(inputs[i].value);
}
}
With a little jQuery, you could do it quite easily, using the attribute starts with selector. We then loop over them, parses their values into integers and sum them up. Something like this:
function InputSum() {
var sum = 0;
$('input[id^="month_"]').each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
}
You could even get rid of the onchange attributes on each input if you modify the code to something like this:
$(function () {
var elms = $('input[id^="month_"]');
elms.change(function() {
var sum = 0;
elms.each(function () {
sum += parseInt($(this).val(), 10);
});
$("#inputSum").text(sum);
});
});
function InputSum() {
var month_0=document.getElementById("month_0").value;// get value from textbox
var month_1=document.getElementById("month_1").value;
var month_2=document.getElementById("month_2").value;
var month_3=document.getElementById("month_3").value;
// check number Can be omitted the
alert(month_0+month_1+month_2+month_3);//show result
}

Categories

Resources