sk1p
sk1p

Reputation: 77

How can I display the sum of certain columns of a table in javascript?

I do not understand javascript at all, I study as needed and I need help I need to sum up the values of certain columns of a table, the rows of which are marked with a checkbox For example: I mark the checkbox in two rows of the table and the sum of 3,4 and 5 columns is summed up and displayed somewhere on the page

Now I managed to find a piece of code that summarizes the value of the checked checkboxes in the form, and displays it on the page I need help in replacing the part that receives the "value" of the input, with the one that gets the values of the cells in the stob = head of the table and sums them

Here is this code

var
    $form = $("#out_form"),
  $allCheckboxes = $("input:checkbox", $form),
  $sumOut = $("#checked-sum"),
  $countOut = $("#checked-count");
  
$allCheckboxes.change(function() {
    var
    sum = 0,
    count = 0;
    $allCheckboxes.each(function(index, el) {
    var 
        $el = $(el),
        val;
    if ($el.is(":checked")) {
        count++;
      val = parseFloat($el.val());
      if (!isNaN(val)) {
        sum += val;
      }
    }
  });
  $sumOut.text(sum);
  $countOut.text(count);
});

HTML

       <form action="" method="post" id="out_form">
            <input type="hidden" name="next" value="{{next}}"/>
            <button type="submit">Check</button>
            <span id="checked-sum">0</span>
            <span id="checked-count">0</span>
            {%csrf_token%}
            <div class="table-view__container">
                <table class="table-view__table">
                    <tbody class="table-view__body">
                        {% for out in filter.qs %}
                        <tr>
                            <td>
                                <label class="custom_Label">
                                    <input type="checkbox" name="checked" value="{{ out.id }}">
                                    <span class="checkmark"></span>
                                </label>
                            </td>
                            <td>{{out.date|date:"d(D).m.Y"}}</td>
                            <td>{{out.ts}}</td>
                            <td>{{out.pl}}</td>
                            <td>{{out.rem}}</td>
                            <td>{{out.comment}}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </form>

It is necessary to sum these 3 columns:

...
<td>{{out.ts}}</td>
<td>{{out.pl}}</td>
<td>{{out.rem}}</td>
...

UPD: I managed to display the amount with the checkbox active, but only the first line:

var
    $form = $("#out_form"),
    $table = $(".table-view"),
  $allCheckboxes = $("input:checkbox", $form),
  $sumOut = $("#checked-sum"),
  $countOut = $("#checked-count");
  
$allCheckboxes.change(function() {
  var
    sum = 0,
    count = 0;
  $allCheckboxes.each(function(index, el) {
    var 
        $el = $(el),
        val;
    if ($el.is(":checked")) {
        count++;
        $form.each(function () {
            var val1 = parseInt(document.querySelector(".ts", this).innerHTML,10);
            var val2 = parseInt(document.querySelector(".pl", this).innerHTML,10);
            var val3 = parseInt(document.querySelector(".rem", this).innerHTML,10);
            var total = (val1 * 1) + (val2 * 1) + (val3 * 1);
            sum += total;
            });
      if (!isNaN(val)) {
        sum += total;
      }
    }
  });
  $sumOut.text(sum);
  $countOut.text(count);
});

Upvotes: 2

Views: 693

Answers (1)

Gass
Gass

Reputation: 9422

JavaScript can be confusing, its definitely not an easy programming language. Sorry for not using your code, but I think its overcomplicating things.

So mainly what this code does is to trigger a function using event handlers on all checkboxes, that sums or substracts from the result variable depending if they are checked or unchecked and then show the result in a <span> tag.

Some key points

  • I used document.querySelectorAll('input[type=checkbox]') to get all the checkbox elements.

  • The following code is to create one event handler for each checkbox element:

boxes.forEach((box) => {
    box.addEventListener("change", function() {
  • The input checkbox element lives inside a <td></td>, so this.closest('td').nextElementSibling is necessary to get the parent tag and then with the help of nextElementSibling we can get the next <td> element of the table which has the value we need to sum or substract.

Snippet

var boxes = document.querySelectorAll('input[type=checkbox]'),
show = document.getElementById('showResult'), result = 0;

boxes.forEach((box) => {
    box.addEventListener("change", function() {
       
       var firstElement = this.closest('td').nextElementSibling,
         secondElement = firstElement.nextElementSibling,
         firstValue = parseInt(firstElement.innerHTML),
         secondValue = parseInt(secondElement.innerHTML);
       
       var sum = firstValue + secondValue;
       this.checked ? result += sum : result -= sum;
       show.innerHTML = result;
    });
});
td {
  border: 1px solid #dddddd;
  text-align: left;
  width:50px;
  text-align:center;
}
span{
  font-size:20px;
}
<table id="table">
  <tr>
    <td><input type="checkbox" id="box1" /></td>
    <td>1</td>
    <td>2</td>
  </tr>
  <tr>
    <td><input type="checkbox" id="box2" /></td>
    <td>3</td>
    <td>4</td>
  </tr>
</table> 
<br>
<br>
<span>Result: </span><span id="showResult">0</span>

Upvotes: 2

Related Questions