0

Angular Datatable: How to get sum of checked values amount dynamically in Datatable.

Have one datatable and checkbox, once we check the checkboxes selected and need to sum of all selected checkbox amount. I tried the following code, getting values but unable to sum. If I uncheck checkbox need to reduce the unchecked box amount. Please suggest the issue.

 checkboxCheckAmountCount(info: any): void {

 var creditAmount = 0;
    var checkedCount = $("#firstTable input:checked").length;
    var amountAdd = false;
    for (var i = 0; i < checkedCount; i++) {
      if (info.index != "") {
        alert(info.index);
        creditAmount += parseFloat(info.index);
      } else {
        creditAmount = 0;
      }
     }
   $("#idCheckBoxLabel").text(creditAmount);
}

Stackblitz

2 Answers 2

2

The following is the function which works fine as per your requirement:

checkboxCheckCount(info: any): void {
  var creditAmount = 0;
  var amountAdd = false;
  $("#firstTable input:checked").each(function() {
    if (info.index != "") {
      creditAmount += parseInt($(this).prop("value"));
    } else {
      creditAmount = 0;
    }
  });
  $("#idCheckBoxLabel").text(creditAmount);
}
Sign up to request clarification or add additional context in comments.

Comments

1

You can use on reduce on all checked items to get the sum as -

checkboxCheckCount(info: any): void {
  var creditAmount = $("#firstTable input:checked").toArray().reduce(function(sum: number, element: any) {
    return sum + Number(element.value);
  }, 0);
  $("#idCheckBoxLabel").text(creditAmount);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.