I'm using jquery-repeater library to create dynamic input in table. Each row will calculate the average value based on keyup event :
=============================
Col A | Col B | Col C | AVG |
=============================
1 | 2 | 3 | 2 |
2 | 3 | 4 | 3 |
...
Col A, B, C are input field. Users can add several rows as needed, and each row will show the average in last column (AVG).
This is my code (View using JQuery-repeater) :
$("input[type=number]", "#table").keyup(function() {
var $parent = $(this).parents('tr');
var allInputs = $("input[type=number]", $parent);
var total = 0;
$.each(allInputs, function() {
total += $(this).val() === '' ? +0 : +$(this).val();
});
$(".avg", $parent).val(total / 3);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="table" class="table repeater" border="1">
<thead>
<tr>
<th>
<center>A - B</center>
</th>
<th>
<center>A - C</center>
</th>
<th>
<center>B - C</center>
</th>
<th>
<center>AVG</center>
</th>
<th>
<center>
<button data-repeater-create id="add_data">
Add Data
</button>
</center>
</th>
</tr>
</thead>
<tbody data-repeater-list="data">
<tr data-repeater-item>
<td><input type="number" name="val1"></td>
<td><input type="number" name="val2"></td>
<td><input type="number" name="val3"></td>
<td><input name="avg" class="avg" readonly></td>
<td>
<center>
<button data-repeater-delete>Delete</button>
</center>
</td>
</tr>
</tbody>
</table>
I expect the function could work in each row, but the actual is the function only works once.
Because your rows is dynamically created so you need to add event to it in this way:
$(document).on("keyup", "#table input[type=number]", function(){})