2010-02-23 73 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