我一直用jquery创建一个表行,列id是已经选择的数据的id。如何计算id动态的'total_price'列的总和(基于数据id)?
这里是我的jquery脚本
function getCorporateService(id){
//get data and parsing to column
$.get("{{ url('salesorder/service')}}/"+id, function(data){
console.log(id);
console.log(data);
$.each(data, function (index, element){
$br = "<tr id='item'>";
$br += "<td> <input class='input-small' type='text' id='order_identifier' name='order_identifier' readonly></td>";
$br += "<td><input class='input-small' type='text' id='service["+id+"]' name='service["+id+"]' value='"+element.service_name+"' readonly></td>";
$br += "<td><select id='order_type["+id+"]' name='order_type["+id+"]'> <option> - </option> <option value='add'>Add</option> <option value='change'>Change</option> <option value='cancel'>Cancel</option> </select></td>";
$br += "<td><input class='input-small' type='text' id='select_plan["+id+"]' name='select_plan["+id+"]'></td>";
$br += "<td><input class='input-mini' type='text' id='qty["+id+"]' name='qty["+id+"]' value='1' onChange='getTotalPrice("+id+")'></td>";
$br += "<td><input class='input-small' type='text' id='unit_price["+id+"]' name='unit_price["+id+"]' onChange='getTotalPrice("+id+")'></td>";
$br += "<td><input class='input-small' type='text' id='total_price["+id+"]' name='total_price["+id+"]' onChange='getTotalPrice("+id+")'></td>";
$br += "<td><textarea class='input-small' id='notes["+id+"]' name='notes["+id+"]'></textarea></td>";
$br += "</tr>";
$(".corporatesvc").append($br);
});
});
}
答案 0 :(得分:3)
要在不向字段添加类的情况下回答您的问题,请使用getTotalPrice中的starts with selector
function getTotalPrice() {
var total = 0;
$("[id^='total_price']").each(function() { // or $(".total_price") if given a class
var val = $(this).val();
total += isNaN(val) || $.trim(val)=="" ? 0 : parseFloat(val); // or parseInt(val,10);
});
$("#total").text(total.toFixed(2)); // or (total) if an int
}
您应该为每个可更改的输入分配一个类名并分配一个处理程序 - 例如onkeyup并使用委托:
$(function() {
$(".corporatesvc").on("keyup",".changeable",function() {
if (this.id.indexOf("qty")==0 ) {
// here you can update siblings
}
getTotalPrice();
});
});
答案 1 :(得分:1)
为每个文本框添加类名。Check this
Link i hope it helps you.
HTML
<input class='input-small total_price' type='text' id='total_price_1' name='total_price_1'>
<input class='input-small total_price' type='text' id='total_price_2' name='total_price_2' >
<input class='input-small total_price' type='text' id='total_price_3' name='total_price_3' >
<p id="classname">
JS
$(".total_price").each(function () {
$(this).keyup(function () {
var sum = 0;
$(".total_price").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
$("#classname").html(sum);
});
});
});