Я хотел бы рассчитать общую сумму строки для каждого элемента, используя поля itemPrice * Кол-во, сумма строки должна быть автоматически заполнена в текстовом поле linePrice. После этого общая сумма автоматически заполняется в поле priceTotal путем суммирования всех цен линий.
У меня возникла проблема с получением каждого значения текстового поля Кол-во и itemPrice в мою функцию JavaScript, поскольку имя (имена) - это Qty0, Qty1, Qty2 ... и itemPrice0, itemPrice1, .. в зависимости от добавленной строки, а также получение окончательных вычислений в соответствующие текстовые поля.
Ниже мой код.
function isNumberKey(evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode != 46 && (charCode < 48 || charCode > 57)))
return false;
return true;
}
$(document).ready(function() {
$(document).on("keyup", ".Qty", calculateTot);
$("button").click(function() {
addrow('tb')
});
});
function calculateTot() {
var sum = 0;
var price = document.getElementById('itemPrice').value;
var qtyPur = parseFloat(this.value);
$(".Qty").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
linePR = price * qtyPur;
}
});
$("#linePrice").val(linePR.toFixed(2));
calculateSum();
}
function calculateSum() {
var sum = 0;
$(".linePrice").each(function() {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
$("#priceTotal").val(sum.toFixed(2));
}
$(document).ready(function() {
var i = 1,
j = 1;
$("#add_row").click(function() {
if (i < 10) {
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
$('#tab_add').append('<tr id = "addr' + (i + 1) + '"></tr>');
i++;
j++;
$('#delete_row').show();
} else {
alert("You can only add upto a maximum of 10 items")
$('#add_row').hide();
}
});
$("#delete_row").click(function() {
if (i > 1) {
var r = confirm('Do you want to delete this item?');
if (r == true) {
$("#addr" + (i - 1)).html('');
i--;
$('#add_row').show();
}
} else {
alert("Entry cannot be deleted")
$('#delete_row').hide();
}
});
}); <!-- Latest compiled and minified CSS -->
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity = "sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin = "anonymous">
<!-- Optional theme -->
<link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity = "sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin = "anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity = "sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin = "anonymous"></script>
<script src = "https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src = "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css"></script>
<script src = "https://code.jquery.com/jquery-2.1.1.js"></script>
<table class = "table table-bordered table-hover" id = "tab_add">
<tbody>
<tr>
<td colspan = "2"><b>Customer Name</b></td>
<td colspan = "1">
<select name = "Per_Name[]" class = "form-control">
<option value = "">Select Customer</option>
<option value = "2000001">John Doe</option>
<option value = "2000002">Jane Doe</option>
<option value = "2000003">Tom Harry</option>
<option value = "2000004">Steve Jobs</option>
</select>
</td>
</tr>
<tr id='addr0'>
<td><b>1</b></td>
<td><b>Select Item</b></td>
<td colspan = "1">
<select name = "Sub_Name[]" class = "form-control">
<option value = "">Select Item</option>
<option value = "1000001">Item A</option>
<option value = "1000002">Item B</option>
<option value = "1000003">Item C</option>
<option value = "1000004">Item D</option>
</select>
</td>
<td><input type = "text" name = "itemPrice0" id = "itemPrice0" class = "itemPrice form-control" placeholder = "Unit Price"></td>
<td><input type = "number" name = "Qty0" id = "Qty0" class = "Qty form-control" onkeypress = "return isNumberKey(event)" placeholder = "Quantity"></td>
<td><input type = "text" name = "linePrice0" id = "linePrice0" class = "linePrice form-control" onkeypress = "return isNumberKey(event)" placeholder = "Line Price" readonly></td>
<th>
<a href = "javascript:void(0);" style = "font-size:18px;width:33%;" id = "add_row" title = "Add More Item"><span class = "glyphicon glyphicon-plus"></span></a>
<a href = "javascript:void(0);" style = "font-size:18px;width:33%;" id = "delete_row" title = "Remove Item"><span class = "glyphicon glyphicon-minus"></span></a>
</th>
</tr>
<tr id='addr1'></tr>
</tbody>
</table>
<table class = "table table-bordered table-hover">
<tr id = "finRow">
<td colspan = "2" width = "75%"><b>TOTAL</b></td>
<td><input type = "text" name = "priceTotal" id = "priceTotal" class = "row-total form-control" disabled></td>
</tr>
</table>


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


functionrosschanged_total1 (a) {
var str = a;
var res = str.split("_");
//alert(res[2]);
var result = res[2];
var rate = parseFloat(document.getElementById("Gridview1_txtgross_" + result).value) * parseFloat(document.getElementById("Gridview1_txtrate_" + result).value);
var scale77 = 2;
// rate = roundNumberV2(rate, scale77);
var gresult = 0.00;
if (isNaN(rate)){
gresult= document.getElementById("Gridview1_txttotal_" + result).value = "";
} else{
gresult= document.getElementById("Gridview1_txttotal_" + result).value = parseFloat(Math.round(rate * 100) / 100).toFixed(2);
}
//GridView1_txtinvamt_0
var gfresult = parseFloat(gresult);
var ggresult = 0.00;
ggresult = gfresult + ggresult;
// $("[id*=lblGrandTotal]").html(ggresult);
//GridView1_txtdelinvnum_0 + GridView1_txtinvamt_0 = GridView1_txtgrosspt_0
// Calculate();
grosschanged_total1(a);
}
function Numerics(text) {
var regexp = /^[0-9]*$/;
if (text.value.search(regexp) == -1) {
text.value = text.value.substring(0, (text.value.length - 1));
alert('Numerics only allowed');
if (text.value.search(regexp) == -1)
text.value = "";
text.focus();
return false;
}
else
return true;
}
Эта часть кода будет вычислять linePrice каждой строки:
$("tr").each(function() {
if ($(this).children("td").length) {
$($($(this).children("td")[5]).children("input")[0]).val(
(($($($(this).children("td")[4]).children("input")[0]).val()) ? Number($($($(this).children("td")[4]).children("input")[0]).val()) : 0) *
(($($($(this).children("td")[3]).children("input")[0]).val()) ? Number($($($(this).children("td")[3]).children("input")[0]).val()) : 0)
)
}
});
Чтобы уменьшить объем обхода DOM, который вам нужно сделать для этого, я предлагаю добавить атрибуты data-* к вашим элементам, чтобы вы могли получить индекс и использовать его для прямой ссылки на другие элементы.
<td><input type = "text" name = "itemPrice0" id = "itemPrice0" data-index = "0" class = "itemPrice form-control" placeholder = "Unit Price"></td>
<td><input type = "number" name = "Qty0" id = "Qty0" data-index = "0" class = "Qty form-control" onkeypress = "if (!isNumberKey(event)){return false;}" placeholder = "Quantity"></td>
<td><input type = "text" name = "linePrice0" id = "linePrice0" data-index = "0" class = "linePrice form-control" onkeypress = "return isNumberKey(event)" placeholder = "Line Price" readonly></td>
Затем в вашей функции $("#add_row").click(function() { мы добавляем data-index='"+j+"' при создании новых элементов ...
$('#addr' + i).html("<td>" + (i + 1) + "</td><td><b>Select Item</b></td><td colspan='1'><select name='Sub_Name" + i + "' class='form-control'><option value=''>Select Item</option><option value='1000001'>Item A</option><option value='1000002'>Item B</option><option value='1000003'>Item C</option><option value='1000004'>Item D</option></select></td><td><input type='text' name='itemPrice" + i + "' id='itemPrice" + j + "' data-index='"+j+"' class='itemPrice form-control' placeholder='Unit Price'></td><td><input type='number' name='Qty" + i + "' id='Qty" + j + "' data-index='"+j+"' class='Qty form-control' onkeypress='return isNumberKey(event)' placeholder='Quantity'></td><td><input type='text' name='linePrice" + i + "' id='linePrice" + j + "' data-index='"+j+"' class='linePrice form-control' onkeypress='return isNumberKey(event)' placeholder='Line Price' readonly></td>");
Наконец, измените обработчик keyup на ...
$("#tab_add").on("keyup", ".Qty", function(e){
var qtyPur = parseFloat(this.value);
if (!isNaN(this.value) && this.value.length != 0) {
// this is where use use the data-index attribute to dynamically generate the target element ids
$("#linePrice"+$(this).data('index')).val(
parseFloat($("#itemPrice"+$(this).data('index')).val()) * qtyPur
);
}
calculateSum()
});
Рад, что смог помочь
Спасибо, Патрик, это прекрасно. Внесу необходимые изменения.