2012-01-31 9 views
0

jQueryを使用してテーブルの列の値を加算しようとしています。これを達成するために、私は最初に各行の最初のセルを見つけてからそれらを加算して、この値を入力フィールドの中に置きます。jQuery:各行の最初のセルについて

これを行うにはどうすればよいですか?

これまでのところ私はしている:

// for each row 
$('table tbody tr').each(function() { 

     $firstCell = $(this).index(1).find('input').val(); 

}); 

だから私は、各行の最初のセルを一緒に追加する必要があります。基本的に$ firstCell変数の各インスタンスが作成されます。例えば

$('output').val(parseInt($firstCell.val()) + parseInt($firstCell.val())); 

誰かが正しい方向に向いていますか?

おかげ

+0

http://stackoverflow.com/questions/6155293/select-最初のtd-in-every-row-w-jquery – ygesher

答えて

1

JS:上記のコード

$('table tbody tr').each(function() { 
    $firstCell = $('td:first-child', this).html(); 
}); 

TRで最初のtd要素を使用すると、HTMLを返します()、ちょうどあなたがTDが値を持っていません知っているように、そのありません入力フィールドも選択もテキストエリアもありません。

0
行います。このような

何かが、コードがある

テストされていないEDIT:最新の変更に基づいて、私はカウンターを追加

// array to hold all cell contents 
var firstCellContents = [], 
    cellCounter = 0; 

// for each row 
$('table tbody tr').each(function() { 

    var $firstCell = $(this).children('td').first(), 
     firstCellContent = $firstCell.text(); 

    firstCellContents.push(firstCellContent); 
    cellCounter += parseInt(firstCellContent, 10); // don't forget the 10! 

}); 

// add all fields to the inputfield: 
$('#inputField').val(firstCellContents.join(',')); 

// or add the total to the inputfield: 

$('#inputField').val(cellCounter); 
関連する問題