Reputation: 226
This is my dynamic table input form.
<table id="calculate">
<tr>
<th>Price</th>
</tr>
<tbody data-role="dynamic-fields">
<tr class="form-inline">
<td>
<div class="input-group">
<input type="text" name="price[]" class="form-control">
</div>
</td>
<td>
<div class="input-group">
<button class="btn btn-primary btn-sm" data-role="add">
Add
</button>
</div>
</td>
</tr>
</tbody>
</table>
<input type="text" name="total_price" id="total_price">
This is jquery that append new form in table when i click button
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-inline [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
}
);
Now I want to input many price by clicking add button and all price should total and append in total_price
$(document).on('change paste keyup', " input[name='price[]']", function(){
updatetotalprice($(this));
});
function updatetotalamount(selector) {
$parent = selector.parent('.input-group').parent('td').parent('tr'); [...$parent.querySelectorAll("tr")].forEach(row => {
$("[name=amount[]]").val()= total;
$("#total_price").val(total.toFixed(2));
})
}
Upvotes: 0
Views: 92
Reputation: 803
Use below script code:
<script>
$(document).on(
'click',
'[data-role="dynamic-fields"] > .form-inline [data-role="add"]',
function(e) {
e.preventDefault();
var container = $(this).closest('[data-role="dynamic-fields"]');
new_field_group = container.children().filter('.form-inline:first-child').clone();
new_field_group.find('input').each(function(){
$(this).val('');
});
container.append(new_field_group);
}
);
function updatetotalamount(selector) {
let $parent = selector.closest('tbody'),
total = 0;
[...$parent[0].querySelectorAll("tr")].forEach(row => {
console.log(($(row).find('input[name="price[]"]')).val());
if(($(row).find('input[name="price[]"]')).val() !== ''){
total += parseInt( ($(row).find('input[name="price[]"]')).val() );
$("#total_price").val(total);
}
})
}
$(document).on('change paste keyup', " input[name='price[]']", function(){
updatetotalamount($(this));
});
</script>
Upvotes: 1