sum input field with separated comma - javascript

sorry for a newbie question, i'm new on javascript.
i already sucess using auto separated thousand with comma using javascript, but my problem is when i want to sum the field, it doesnt recognize the comma ( when my number already 1000, it automatically add a , into 1,000). i already tried to replace the comma, but its still doesnt work. any suggestion for my fault?
this is some my google script
<script type="text/javascript">
$(document).ready(function(){
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//this.value.replace( /,/g,"");
//add only if the value is number
if(!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value.replace(/,/g,""));
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
</script>
thanks before
regards, liu

May this solution help you?:
$(document).ready(function(){
$(".txt").on("keyup", function(){
calculateSum();
});
function calculateSum() {
var sum = 0;
$(".txt").each(function() {
//cleaning the number / removing commata
var number = this.value.replace(/,/g, "");
//add only if the CLEANED value is a number
if(!number.length || isNaN(number)) return;
sum += parseFloat(number);
});
$("#sum").html(sum.toFixed(2));
}
calculateSum();
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><input class="txt" placeholder="Number 1"></div>
<div><input class="txt" placeholder="Number 2"></div>
<div><input class="txt" placeholder="Number 3"></div>
<div id="sum"></div>

Related

JQuery DOM manipulation: sum of 2 numbers generate NaN even if using parseInt()

I have multiple input type="number" on my page. They are dinamically generated each time a user clicks on a "add-form-row" button. I want to give as value to a h2 element in my DOM based on the sum of each of these input each time a new input is added. When I try to sum the inputs, though, a NaN is returned. How can I fix this?
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
//cloneMore('.form-row:last', 'elements');
// here starts the sum logic
var tot = 0;
currentTotal = $('.form-row').find('input[type=number]').each(function() {
numberPrice = parseInt($(this).val())
tot += numberPrice
});
$('.totalPrice').text(`<span>${tot}</span>`)
return false;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-row">
<input type="number" value="1">
<input type="number" value="2">
<button class="add-form-row">add</button>
<div class="totalPrice"></div>
</div>
If any of the input value is ="", i.e nothing, the total will be NaN, because parseInt("") = NaN, so maybe adding a condition like this can solve your problem:
$(document).on('click', '.add-form-row', function(e){
e.preventDefault();
//cloneMore('.form-row:last', 'elements');
// here starts the sum logic
var tot = 0;
currentTotal = $('.form-row').find('input[type=number]').each(function() {
if($(this).val() != ""){
numberPrice = parseInt($(this).val());
tot += numberPrice;
}
});
$('.totalPrice').text(`<span>${tot}</span>`);
return false;
});

Sum up all text boxes with a particular class name?

I have a grid, with one of the columns containing a textbox, where a user can type in a dollar amount. The text boxes are declared as:
<input class="change-handled" sub-category-id="83" data-id="" style="text-align: right; width: 100%" type="number" value="">
Some are all decorated with the class "change-handled".
What I need to do, is, using javascript/jquery, sum up all the boxes which are using that class, and display the total elsewhere on the screen.
How can I have a global event, that would allow this to occur when ever I exit one of the boxes (i.e: Tab out, or ENTER out).
At the moment, I have an event which doesn't do much at the moment, which will be used:
$('body').on('change', 'input.change-handled', SaveData);
function SaveData() {
var dataId = $(this).attr('data-id');
var categoryId = $(this).attr('sub-category-id');
var value = $(this).val();
}
How can I use that SaveData event, to find all the editboxes with the 'change-handled' class, sum up their values, and display it somewhere?
In plain JavaScript:
var changeHandled = [].slice.call(document.querySelectorAll('.change-handled'));
var total = document.querySelector('.total');
function calc() {
total.textContent = changeHandled.reduce(function(total, el) {
return total += Number(el.value);
}, 0);
}
changeHandled.forEach(function(el) {
el.onblur = calc;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
I think what you're looking for is the blur event.
$('body').on('blur', 'input.change-handled', UpdateTotal);
function UpdateTotal() {
var total = 0;
var $changeInputs = $('input.change-handled');
$changeInputs.each(function(idx, el) {
total += Number($(el).val());
});
$('.total').text(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" class="change-handled">
<input type="number" class="change-handled">
<input type="number" class="change-handled">
Total: $<span class="total">0</span>
Here's how you can sum up the values:
var total = 0;
$(".change-handled").each(function(index, box) {
total += parseInt($(box).val(), 10);
});
You would then display them by using the text or html functions provided by jQuery on elements.
This can be used from anywhere in your code, including the event handler.

Calculate sum and multiply its value

I'm calculating the sum of a and b and putting it in text box named sum.
After I enter a number in number text box, it should calculate the final = sum * number.
<input type="text" class="txt_1_0" name="a" />
<input type="text" class="txt_1_0" name="b" />
<input type="text" id="sum" name="sum" />
<input type="text" class="number" name="number" />
<input type="text" class="final" name="final" />
I tried the following:
$(document).ready(function() {
$(".txt_1_0").change(function() {
var total = 0.00;
var textbox3 = 0.00; // this gonna be your third textbox
$(".txt_1_0").each(function() {
total += parseFloat(this.value) / 5;
});
textbox3 = $("#sum").val((total).toFixed(2));
});
});
How do I get the number value and calculate final?
You haven't actually added any function that would do the final calculation. So to multiply the sum (subtotal) with number, do the following:
$(".number").change(function () {
var final = $("#sum").val() * $(this).val();
$('.final').val(final);
});
Here is a demo - note that I have removed the division by 5 from your previous function as it didn't make sense from the the way your question was asked.
Or you can use keyup event with this jQuery code Fiddle
<script type="text/javascript">
$(document).ready(function(){
$('input[type="text"]').on('keyup',function(){
var a=parseFloat($('.txt_1_0:first').val())
var b=parseFloat($('.txt_1_0:last').val())
if(a && b){$('#sum').val(a+b)}
var number=$('.number').val()
if(number){
$('.final').val($('#sum').val()*number)
}
})
})
</script>

Calculate form inputs onChange

I have a dynamic form that is being generated based on what the user adds to the cart.
For example, the form will looks something like this,
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Form</title>
</head>
<body>
<form action="" name="cart" id="cart">
<input type="text" name="sku1">
<input type="text" name="sku2">
<input type="text" name="sku3">
<input type="text" name="sku4">
<input type="text" name="sku5">
<div class="sum" id="sum"> Total: {SUM SHOULD SHOW UP HERE)</div>
<button name="submit">Send</button>
</form>
</body>
</html>
But those input fields are generated automatically and may be more or less than 5 fields.
How to calculate those input SUM value and output to SUM div without page refresh?
JavaScript/jQuery?
$('button[name="submit"]').click(function () {
var sum = 0;
$('#cart input[name^="sku"]').each(function () {
var val = isNaN(+this.value) ? 0 : +this.value;
sum += val;
});
$('#sum').text(sum);
});
Or
var inp = $('#cart input[name^="sku"]');
inp.change(function () {
var sum = 0;
inp.each(function () {
var val = isNaN(+this.value) ? 0 : +this.value;
sum += val;
});
$('#sum').text(sum);
});
Attribute Starts With Selector [name^="value"]
.change()
isNaN()
You can use the onsubmit attribute of the form to do whatever you want to before the form gets submitted. You can change action attribute also. You can also preventDefault as said here-
jQuery on submit preventDefault() does not works
You can give the elements a class, amountForTotal, and use a function to calc the total, which you can add to a button, or onchange event of an input.
function calcTotal( $elements ){
var total = 0;
$elements.each(function(){
// if the input has no value, add 0, if it has, add the value
total+= this.value.length===0 ? 0 : parseInt(this.value);
})
return total; // return the total
}
$elements = $('.amountForTotal'); // select them
// Bind an event to recalc the total
$elements.on('keyup', function(){
alert( calcTotal($elements) );
});
In this code I provided the selector as input. This is luxery, not needed, you can add that selector in the function, but this way it can be used more flexible. You can use the [name^=*] selector here, but its slower than a class, which you might notice in large documents.
Also, In my code I check if it has to no value to prevent errors. You can expand this to test if the input is actualy a number.

jquery calculate html values next to checked checkboxes

My head is not thinking right today. Could any of you help? =)
Only checked int values in second column need to be calculated and alerted in sum.
<table width="100%">
<tr><td>Product Name</td><td>Price $</td></tr>
<tr><td><input type="checkbox"> Product 1</td><td>200</td></tr>
<tr><td><input type="checkbox"> Product 2</td><td>300</td></tr>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$('input').change(function() {
var sum = 0;
$("input:checked").each(function(){
sum += parseInt($("input:checked").closest('td').next().html());
});
alert(sum);
});
</script>
Thanks.
Looks like you should be using $(this) inside the .each() to find the closest <td> to the currently selected checkbox in the loop.
// Bind to all checkboxes...
$('input[type="checkbox"]').change(function() {
var sum = 0;
$("input:checked").each(function(){
// Use $(this) here
sum += parseInt($(this).closest('td').next().html(), 10);
// Always use the optional radix to parseInt() -----^^^^^
});
alert(sum);
});
Try this:
$('input:checkbox').change(function() {
var sum = 0;
$("input:checked").each(function() {
sum += parseInt($(this).closest('td').next().text(), 10);
});
alert(sum);
});
You need to listen for the change event on all checkboxes, not only those :checked. Also, be sure to pass the radix parameter to parseInt. Finally, this will refer to the item being evaluated in the each function.
Example: http://jsfiddle.net/38AeT/

Categories

Resources