I want to sum each column with the next column that is in the same position in the next .row. For example:
All columns are created dynamically and have the same class. Can you help me to do it (with jQuery o Javascript)?
$(document).ready(function() {
var sum = 0;
$('.col-1').each(function(index) {
sum += parseFloat($(this).text().replace(',', ''));
});
$('.total').html(sum);
});
<div class="row">
<div class="col-1"><input type="number" /></div>
<div class="col-1"><input type="number" /></div>
<div class="col-1"><input type="number" /></div>
</div>
<div class="row">
<div class="col-1"><input type="number" /></div>
<div class="col-1"><input type="number" /></div>
<div class="col-1"><input type="number" /></div>
</div>
<div class="row">
<div class="col-1"><input type="number" /></div>
<div class="col-1"><input type="number" /></div>
<div class="col-1"><input type="number" /></div>
</div>
<div class="result">
<div class="col-1"></div>
<div class="col-1"></div>
<div class="col-1"></div>
</div>
<div class="result">
<div class="col-1">(( row1 col1(first-child) + row2 col1(first-child) + row3 col1(first-child) = 12 ))</div>
<div class="col-1">(( row1 col2(second-child) + row2 col2(second-child) + row3 col2(second-child) = 8 ))</div>
<div class="col-1">(( row1 col3(third-child) + row2 col3(third-child) + row3 col3(third-child) = 6 ))</div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
2
Answers
First find how many rows there are. If it’s constant, then use a constant number instead.
Then just run through each
.row
except for results, and add-up to totals.Finally show results.
Plain JavaScript Solution
Using plain JavaScript you can sum the columns with one (long) line of code.
This solution uses the nth-child(index) selector to get all the values in a column. The + prefix on innerText coerces the string to a number when doing the sum. See browser support for the
:not
selector before using.Update
In a follow up question, OP asks how to dynamically sum inputs in a column. This can be done by modifying the original code to select the inputs and sum their values. We also need to reset the column sum during each update. This is done using ternary operator that sets the previous sum to zero when the index is zero. The snippet contains additional code for the event handler and validation.
Snippet
Open and run the snippet to understand how it works.