2010-02-23 51 views
0

我有一个模仿发票输入表单的HTML表单。jQuery枚举动态表

这是我加载发票项目的方式(用户选择其中直通使用jQuery自动完成列表):

$(document).ready(function() { 
     $("#Products").focus().autocomplete('<%=Url.Action("GetProducts", "Product") %>', { 
      dataType: 'json', 
      parse: function(data) { 
       var rows = new Array(); 
       for (var i = 0; i < data.length; i++) { 
        rows[i] = { data: data[i], value: data[i].product_name1, result: data[i].product_name1 }; 
       } 
       return rows; 
      }, 

      formatItem: function(row, i, n) { 
       return row.product_PrettyId + ' - ' + row.product_name1 + ' (' + row.product_price + ' €) '; 
      }, 
      width: 900, 
      minChars: 0, 
      max: 0, 
      mustMatch: true 
     }); 

     $("#Products").result(function(event, data, formatted) { 
      if (data) { 
       $(this).parent().next().find("input").val(data["product_id"]); 
       $("#InvoiceItems > tbody").append(
        "<tr>" + 
        "<td>num</td>" + 
        "<td>" + data["product_PrettyId"] + "</td>" + 
        "<td>" + data["product_name1"] + "</td>" + 
        "<td>" + data["product_price"] + "</td>" + 
        "<td></td>" + 
        "<td>1</td>" + 
        "<td>" + data["product_price"] + "</td>" + 
        "</tr>"); 
      } 
     }); 

后各发票项目加到我需要枚举我正在创建表 - 计数的项目,将价格与数量相乘并且将所有项目相加。

我该怎么做?

+0

你能也许提供如果可能的话,你已经有了什么简单的例子你试图达到什么目标? – Rune 2010-02-23 21:34:52

回答

2

您可能希望将某些类添加到特定的tds中,例如数量,价格以及项目总数,每次添加新项时都可以更新计数器并将其存储在隐藏字段中并阅读从该值

编辑:在功能

function functionName() { 
var itemCounter = 0; 
$('#InvoiceItems tr').each(function() { 
    itemCounter += 1; 
    //this loops through each row in the table 
    var quantity = parseFloat($('td.quantity', this).text()); 
    quantity = isNaN(quantity) ? 1 : quantity;//if a number isn't parsed, replace it with 1 
    var price = parseFloat($('td.price', this).text()); 
    price = isNaN(price) ? 0 : price; 
    var total = quantity * price; 
    //do something with the total 
}); 
} 

你可以调用这个函数每当增加了新的项目,以便总计将永远是最新的包装。每圈

+0

你的代码看起来很好,但我遇到了问题。 val()的行返回“undefined”,因此总数是NaN。什么可能是错的? – mare 2010-02-24 10:50:33

+0

我将用一些NaN检查来更新代码 – Jimmy 2010-02-24 13:08:00

+0

您还可以在输入上添加验证检查以确保值为数字 – Jimmy 2010-02-24 13:36:08