2011-06-08 74 views
2

我正在構建一個接口,它會在檢查輸入時計算總數(基於相鄰輸入)。當一個輸入被檢查時,我得到的其他輸入值在同一個<td>,然後建立一個總計。我應該使用數組還是對象來構建摘要?

例子:http://jsfiddle.net/vdunm/1/

我需要建立總計爲被檢查,我只是似乎無法找到如何做的正確路徑的所有複選框摘要(按名稱分組)。

所以,如果你檢查的第3行(2個FOOS和1條)我所要的輸出是這個樣子:

FOO: 100 
BAR: 30 

這裏是我的HTML:

<table id="test"> 
    <tr> 
     <td> 
      <input type="checkbox" name="id" size="20" value="100" /> 
      <input type="text" name="name" size="20" value="FOO" /> 
      <input type="text" name="cost" size="20" value="10.00"> 
      <input type="text" name="quantity" size="20" value="1"> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <input type="checkbox" name="id" size="20" value="200" /> 
      <input type="text" name="name" size="20" value="BAR" /> 
      <input type="text" name="cost" size="20" value="10.00"> 
      <input type="text" name="quantity" size="20" value="3"> 
     </td> 
    </tr> 
    <tr> 
     <td> 
      <input type="checkbox" name="id" size="20" value="300" /> 
      <input type="text" name="name" size="20" value="FOO" /> 
      <input type="text" name="cost" size="20" value="10.00"> 
      <input type="text" name="quantity" size="20" value="9"> 
     </td> 
    </tr> 
</table>  

的jQuery:

// when the id checkbox is clicked 
$('table').delegate('input[name=id]', 'click', function(){ 

    // set the total at 0 
    var totalCost = 0; 

    // loop through each checked line 
    $('input[name=id]:checked').each(function(){ 

     // get the input values for this checked row 
     var thisRow = $(this).parent(), 
      person = thisRow.find('input[name=name]').val(), 
      qty = thisRow.find('input[name=quantity]').val(), 
      cost = thisRow.find('input[name=cost]').val(); 

     // get total 
     var lineCost = cost * qty; 

     // add to the grand total 
     totalCost+=parseFloat(lineCost); 

    }); 

    // output the total cost 
    $('#output').empty().append(totalCost); 

}); 

我應該建立一個數組還是一個對象?我基本上只需要得到所有已經檢查過的名字,並且顯示每個名字的總和。我只需要一個正確的方向。

+2

你想要什麼?性能?最短的代碼量?你可以去做很多不同的方式,但你想要做什麼? – Niklas 2011-06-08 20:26:55

+0

好問題,不會有大量的複選框,所以它不應該太重。我猜代碼的可讀性是可以拍攝的。 – jyoseph 2011-06-08 20:55:13

回答

1

只要沒有真正的排序要求,您應該構建一個對象。

您彙總後,右鍵你可以有這些行:

totalCost += parseFloat(lineCost); 

if(totals[person] == null) { 
    totals[person] = 0; 
} 

totals[person] += totalCost; 

您還需要定義:

var totals = {}; 

那會去你的循環以上。

相關問題