Calculating Sum of Checked Checkboxes

Calculating sum of checked checkboxes

Remove the break which will stop the for loop. Your for loop is only going to get the value of the first checked checkbox that way. Your logic is flawed; just because you have found one checked checkbox does not mean that your calculations are finished. You need to add the values of all the checked checkboxes.

var calculator = document.querySelector("form");
function extras() { var extrasPricing = new Array(); extrasPricing["candles"] = 5; extrasPricing["inscription"] = 10; extrasPricing["decoration"] = 25; extrasPricing["special"] = 50;
var extrasCost = 0; var extras = calculator.elements["extras"];
for (var i = 0; i < extras.length; i++) { if (extras[i].checked) { extrasCost = extrasCost + extrasPricing[extras[i].value]; //Do not break here } } return extrasCost;}
function calculateTotal() { calculator.total.value = "$" + extras();}
<form><fieldset><legend>Select Extras</legend><label><input type="checkbox" name="extras" value="candles" onclick="calculateTotal()">Candles</label><br><label><input type="checkbox" name="extras" value="inscription" onclick="calculateTotal()">Inscription</label><br><label><input type="checkbox" name="extras" value="decoration" onclick="calculateTotal()">Decoration</label><br><label><input type="checkbox" name="extras" value="special" onclick="calculateTotal()">Special Frosting & Icing</label></fieldset>
<input type="text" name="total" readonly><input type="submit" value="Submit"></form>

Get the Sum of checked checkbox for each row of table

$(this).parents("tr").children("td").find('input[type=checkbox]:checked')

When you tick the checkall checkbox, it will be matched by this selector. It doesn't have an explicit value set, so .val() will return the string "on".

Obviously, the string "on" cannot be converted to an integer, so your total will become NaN.

Exclude the .checkall checkbox from your selector, and your code will work.

$(this).parents('tr').find(':checkbox:checked').not(".checkall").each(...

Updated fiddle

NB: You should also pay attention to the jQuery documentation - $(document).ready(fn) has been deprecated since v3. Use $(fn) instead.


Edit: Based on your updated Fiddle posted on CodeProject, you just need to trigger the change event of your checkbox after you've updated it from the SelectAll function:

table.find('td:nth-child(' + columnIndex + ') input').prop("checked", obj.checked).change();

Fixed updated Fiddle

How get the sum of all the checkbox values of checked items

This one has fixed all the errors you made in your markup, and simplified the code by alot.

const output = document.getElementById('priceSection');

const totalPrice = () => [...document.querySelectorAll('#prices input[type=checkbox]:checked')]
.reduce((acc, {
dataset: {
price
}
}) => acc + +price, 0);

document.getElementById('prices').addEventListener('change', () => output.textContent = totalPrice());
<div id="prices">
<input type="checkbox" data-price="10" />
<input type="checkbox" data-price="20" />
<input type="checkbox" data-price="30" />
</div>
<div id="priceSection"></div>

How to calculate total sum of checkbox values depend on quantity in textbox

To achieve this you should loop through the table body's row for that use the code as

 $('table tbody tr').each(function() 
{
//do something
});

and then find the checkbox in that row. You can check if the check box is checked by using $tr.find('input[type="checkbox"]').is(':checked') this code. It will find a check box in the row and it will check whether it is checked or not.

var $columns = $tr.find('td').next('td').next('td'); This code is used to retrieve the column Quantity.

We call the function calculateSum() to calculate the sum coast of checked rows in both textbox change event and checkbox change event.

$(document).ready(function() {

function calculateSum(){
var sumTotal=0;
$('table tbody tr').each(function() {
var $tr = $(this);

if ($tr.find('input[type="checkbox"]').is(':checked')) {

var $columns = $tr.find('td').next('td').next('td');

var $Qnty=parseInt($tr.find('input[type="text"]').val());
var $Cost=parseInt($columns.next('td').html().split('$')[1]);
sumTotal+=$Qnty*$Cost;
}
});

$("#price").val(sumTotal);

}

$('#sum').on('click', function() {

calculateSum();
});

$("input[type='text']").keyup(function() {
calculateSum();

});

$("input[type='checkbox']").change(function() {
calculateSum();

});



});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="sum" type="button">Calculate</button><br/>

<table>
<tr style="background-color: silver;">
<th>Check it</th>
<th>Estimate item</th>
<th>Quantity</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" name="chck" value="450" /></td>
<td>Remove Tile</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$450</td>
</tr>
<tr>
<td><input type="checkbox" class="chck" value="550" /></td>
<td>Remove Tub</td>
<td><input type="text" name="qnty" value="1"></td>
<td>$550</td>
</tr>
</table>

<p>Calculated Price: $<input type="text" name="price" id="price" disabled /></p>

Sum up cell values in HTML table if checkbox is checked

You have to change the line td[i] because it's not defined as the error suggests. So, consider using bare td and accessing its innerText. It'll return a string with the value, which you have to convert to a float number with parseFloat. Finally, you must set the precision you want to subTotal so that it will print with the number of decimals you want.

function calculate() {
const ele = document.getElementsByTagName('input');
let table = document.getElementById("myTable");
let tr = table.getElementsByTagName("tr");
let subTotal = 0;
for (var i = 0; i < ele.length; i++) {
let td = tr[i].getElementsByTagName("td")[1];
let price = parseFloat(td.innerText); // change here
if (ele[i].type == 'checkbox' && ele[i].checked == true)
subTotal += price;
}
document.getElementById("val").innerHTML = "The subtotal is " + subTotal.toFixed(2); // and set precision here
}
<!DOCTYPE html>
<html>

<body>

<table id="myTable">
<tr>
<td>T-Shirt</td>
<td>9.99</td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td>Pants</td>
<td>49.99</td>
<td><input type="checkbox"></td>
</tr>
</table>
<span id="val">The subtotal is: </span>
<button onclick="calculate()">Calculate subtotal</button>

</html>

How to sum value of checked changed checkbox jquery?

First I moved declaration of variable count inside the change function to avoid invalid value in repeating the checked-unchecked

Then you should cast the value of checkbox to a numeric so your summation gives correct values

check this fiddle, it works

How to calculate sum of selected checkbox value?

You can use:

 $('.table-grid2 input').change(function(){
var total = 0;
$('.table-grid2 input').each(function() {
if (this.checked)
{
total += parseInt(this.value);
}
});
$('#total').html(total);
});


Related Topics



Leave a reply



Submit