jquery calculate html values next to checked checkboxes - javascript

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/

Related

sum input field with separated comma

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>

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;
});

Increment input field value with jQuery

I want every time when user enter number ,print the new one + old one in console
here is html script
<input type="number"value=""/>
<button>click</button>
my jquery code
$("button").click(function (){
var x = $("input").val();
x+=x;
console.log(x);
});
You have to initialize the value outside somewhere to keep its state.
html
<input type="number" id="inp" value=""/>
<button>click</button>
js
var x = 0;
$("button").click(function (){
var y = parseInt($("#inp").val());
x+=y;
console.log(x);
});
hope this will help to you. refer the working demo.
var thevalue = 0;
$("#click").click(function(){
$("#display").text("The Value is :");
var theinput_value = parseInt($("#num").val());
thevalue += theinput_value;
$("#display").append(thevalue);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Enter the nubmer : <input type="number" id="num"><button id="click">Click on me !</button>
<br>
<p id="display">The Value is :</p>
You just need to make sure x is a global variable so you can save it's value and used each time the click handler is triggered.
I added input casting to avoid string concatenation when using the addition assignment operator.
var x = 0;
$("button").click(function (){
// Get the input
var current_input = parseInt($("input").val());
// If input is not a number set it to 0
if (isNaN(current_input)) current_input = 0;
// Add the input to x
x+=current_input;
// Display it
console.log(x);
});

getting specific table rows based on the value within an input being greater than zero

I need to get the number of rows in a table where an input within the row has a value greater than zero. so for example i have
<table>
<tr><td><input type="text" value="23.4"/></td></tr>
<tr><td><input type="text" value="39.5"/></td></tr>
<tr><td><input type="text" value="14.4"/></td></tr>
<tr><td><input type="text" value="0"/></td></tr>
<tr><td><input type="text" value="89"/></td></tr>
</table>
so the query must return a total row count of 4 using the above example.
I have managed to get the following to work as the quickest and easiest solution to this problem
var counter = 0;
$('table tr').each(function(){
if(parseFloat($(this).find('input').val()) > 0){counter++;}
});
the value increments for each value found greater than zero. thanks for the help guys
Get the rows, then filter on inputs that you filter on wether they have a value greater than zero.
var numb = $('table tr').filter(function() {
return $(this).find('input').filter(function() {
return this.value > 0;
}).length > 0;
}).length;
This would allow mulitple inputs in each row, and if any input has a value greater than zero, the row is counted
FIDDLE
well you need jQuery, then retrieve all '.tr input', then check the value
var res = $('tr input').filter(function(index){
// need multiplicate by 1 to cast as number because input values are always strings
return (this.value*1) > 0;
});
console.log('res.length : ', res.length);

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.

Categories

Resources