У меня есть динамическая таблица, которая вычисляет общий столбец в конце каждой строки в зависимости от входных значений, но я не могу получить общую сумму этой строки?
Я создаю свою таблицу с помощью:
function calc() {
var td = document.querySelectorAll('#item_table > tr > td:last-child');
var stotal = [].reduce.call(td, function(a, b) {
return a + parseInt(b.innerText);
}, 0);
document.getElementById('sub_total').innerText = stotal;
}
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_name[]" oninput = "calc();calcSub()" class = "form-control item_name" size = "16" /></td>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_quantity[]" oninput = "calc()" class = "form-control item_quantity" /></td>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_unit[]" oninput = "calc()" class = "form-control item_unit" /></td>';
//NEW ONES!!!!!!!!!!!!!!!
html += '<td><select name = "item_glass[]" oninput = "calc()" class = "form-control item_glass"><option>Select Glass Type</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><select name = "item_splash[]" oninput = "calc()" class = "form-control item_splash"><option value = "0">Select Splash</option><?php echo fill_unit_select_box3($connect); ?></select></td>';
html += '<td><input type = "text" value = "-" name = "item_colour[]" oninput = "calc()" class = "form-control item_colour" /></td>';
html += '<td><input type = "number" min = "0" value = "0" oninput = "calc()" name = "item_HQuan[]" class = "form-control item_HQuan" /></td>';
html += '<td><select name = "item_HDiam[]" oninput = "calc()" class = "form-control item_HDiam"><option value = "0">Select Hole Diameter</option><?php echo fill_unit_select_box2($connect); ?></select></td>';
html += '<td><input type = "number" min = "0" value = "0" oninput = "calc()" name = "item_CQuan[]" class = "form-control item_CQuan" /></td>';
//Total
html += '<td><input type = "text" value = "0.0" name = "item_Total[]" id = "item_Total[]" class = "form-control item_Total" disabled/></td>';
html += '<td><button type = "button" name = "remove" class = "btn btn-danger btn-sm remove">Delete Item<span class = "glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class = "table table-bordered" id = "item_table">
<tr id = "titles">
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Glass Type</th>
<th>Sparkle or Glaze</th>
<th>Colour Code</th>
<th>Hole Quantity</th>
<th>Hole Diameter</th>
<th>Cut-out Quantity</th>
<th>Item cost £ (excl. Vat)</th>
<th><button type = "button" name = "add" class = "btn btn-success btn-sm add"><span class = "glyphicon glyphicon-plus"></span>Add Item</button></th>
</tr>
</table>
<div class = "form-group">
<label for = "job_ref">Sub Total</label>
<input type = "text" id = "sub_total" class = "form-control sub_total" name = "sub_total" placeholder = "0" value = "0" readonly/>
</div>Еще одна попытка, но всегда равная 0 независимо от ввода:
function calcSub(){
var cls = document.getElementById("item_Total[]").getElementsByTagName("td");
var sum = 0;
for (var i = 0; i < cls.length; i++){
if (cls[i].className == "countable"){
sum += isNaN(cls[i].value) ? 0 : parseInt(cls[i].value);
}
}
document.getElementById('sub_total').value = sum;
};
Они так или иначе делают это, я не могу понять?
Над функцией создания динамических таблиц
У вашего стола есть tbody ??
Я обновил свой пост, включив в него таблицу, и попробовал его без tbody - все тот же результат
Как вы хотите его рассчитать? Каждый раз, когда пользователь нажимает кнопку «Добавить элемент»? или что?
Каждый раз, когда общий столбец изменяется, промежуточный итог должен обновляться.
также вставьте функцию calcSub
Где должен отображаться результат расчета?
@FDavidov Я обновил свой вопрос другим возможным решением, в котором указывается, куда должен идти ответ
Я не вижу в вашем коде элемента с идентификатором "sub_total". Я что-то пропустил?
@FDavidov внизу таблицы?
Я вижу item_Total, а не sub_total. Фактически, я просмотрел страницу, и sub_total нигде не нашел.



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


function calcSub(){
var totalPrice = 0;
$(".item_Total").each(function(){
totalPrice += parseInt($(this).val());
$(".sub_total").val(totalPrice);
});
Ответ привезен из поста: Как суммировать значения из столбца таблицы и обновлять при удалении / добавлении новой строки
Попробуйте что-то вроде этого кода
$(document).on('click', '.add', function(){
var html = '';
html += '<tr>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_name[]" class = "form-control item_name" size = "16" /></td>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_quantity[]" class = "form-control item_quantity" /></td>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_unit[]" class = "form-control item_unit" /></td>';
//NEW ONES!!!!!!!!!!!!!!!
html += '<td><select name = "item_glass[]" class = "form-control item_glass"><option>Select Glass Type</option><?php echo fill_unit_select_box($connect); ?></select></td>';
html += '<td><select name = "item_splash[]" class = "form-control item_splash"><option value = "0">Select Splash</option><?php echo fill_unit_select_box3($connect); ?></select></td>';
html += '<td><input type = "text" value = "-" name = "item_colour[]" class = "form-control item_colour" /></td>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_HQuan[]" class = "form-control item_HQuan" /></td>';
html += '<td><select name = "item_HDiam[]" class = "form-control item_HDiam"><option value = "0">Select Hole Diameter</option><?php echo fill_unit_select_box2($connect); ?></select></td>';
html += '<td><input type = "number" min = "0" value = "0" name = "item_CQuan[]" class = "form-control item_CQuan" /></td>';
//Total
html += '<td><input type = "text" value = "0.0" name = "item_Total[]" id = "item_Total[]" class = "form-control item_Total" disabled/></td>';
html += '<td><button type = "button" name = "remove" class = "btn btn-danger btn-sm remove">Delete Item<span class = "glyphicon glyphicon-minus"></span></button></td></tr>';
$('#item_table').append(html);
});
$(document).on('change', 'input', function() {
$("table tr").each(function(ind, el) {
var sum = 0; $(this).find("input:not(:last)").each(function(indx, ele) {
sum += $(ele).val();
});
$(this).find("input").last().val(sum);
});
});<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class = "table table-bordered" id = "item_table">
<tr id = "titles">
<th>Quantity</th>
<th>Width</th>
<th>Height</th>
<th>Glass Type</th>
<th>Sparkle or Glaze</th>
<th>Colour Code</th>
<th>Hole Quantity</th>
<th>Hole Diameter</th>
<th>Cut-out Quantity</th>
<th>Item cost £ (excl. Vat)</th>
<th><button type = "button" name = "add" class = "btn btn-success btn-sm add"><span class = "glyphicon glyphicon-plus"></span>Add Item</button></th>
</tr>
</table>
<div class = "form-group">
<label for = "job_ref">Sub Total</label>
<input type = "text" id = "sub_total" class = "form-control sub_total" name = "sub_total" placeholder = "0" value = "0" readonly/>
</div>Но учтите это:
1-create a class for columns you want to be calculated and modify its jquery selector.
2-ensure the input values always are numeric, then convert them into
Number.3-for the
Sub Totalinsert special jquery code you want. (I did not add that, because I don't know how exactly calculate its value)
где вы определяете функцию
calc()?