0

問題:4つの列(名前、価格、数量、値)を持つhtmlテーブルがあります。数量フィールドには入力タグがあります。基本的に、誰かが数量フィールドに数値を書き込んでからボタンを押すと、スクリプトは各行の価格と数量のセルを乗算し、それぞれの値のセルに書き込む必要があります。次に、最終的にすべての値を追加し、テーブルの後に書き込みます。

簡単そうに見えますが、javascript/jqueryのドキュメントからは理解できません。

これは私のhtmlコードです:

<form>
<table border="0" cellspacing="0" cellpadding="2" width="400" id="mineraltable">
<tbody>
<tr>
<td valign="top" width="154">Ore</td>
<td valign="top" width="53">Price Per Unit</td>
<td valign="top" width="93">Quantity</td>
<td valign="top" width="100">Value</td></tr>
<tr>
<td valign="top" width="154"><strong>Arkonor</strong></td>
<td id="11" valign="top" width="53">1</td>
<td valign="top" width="93"><input name="12"></td>
<td id="13" valign="top" width="100">&nbsp;</td></tr>
//Lots more of these rows... all Price rows have an ID with a 1 at the end, i.e. 21, 31, 41,. ...., 
//all the text inputs have a 2 at the end of the name, and all Values have a 3 at the end.
</tbody></table></form>
<p id="result">Your value is: </p>
<button type="button">Calculate</button>
4

1 に答える 1

2

jsfildde here で基本的な解決策を実行しました。

私はあなたのhtmlを少し整理したことに注意してください。

また、無効な入力などをチェックするために追加の作業を行う必要がありますが、アイデアは得られるはずです。

HTML:

    <table border="0" cellspacing="0" cellpadding="2" width="400" id="mineraltable">
    <thead>

<tr>
<td valign="top" width="154">Ore</td>
<td valign="top" width="53">Price Per Unit</td>
<td valign="top" width="93">Quantity</td>
<td valign="top" width="100">Value</td></tr>
<tr>
        </thead>
<tbody>
<td valign="top" width="154"><strong>Arkonor</strong></td>
<td class="price" id="11" valign="top" width="53">1</td>
<td class="quantity" valign="top" width="93"><input name="12" value="1"></td>
<td class="value" id="13" valign="top" width="100">&nbsp;</td>
    </tr> 
</tbody>
    </table>
<p id="result">Your value is: </p>
<button type="button">Calculate</button>​

Javascript:

    $('button').click(function() {
    var total = 0;

    $('#mineraltable tbody tr').each(function(index) { 

        var price = parseInt($(this).find('.price').text()); 
        var quantity = parseInt($(this).find('.quantity input').val()); 
        var value = $(this).find('.value');
        var subTotal = price * quantity;

        value.text(subTotal);
        total = total + subTotal;

    });

    $('#result').text('Your value is: '+total);
});​
于 2012-09-03T01:02:29.053 に答える