0

私は次のようなものに見えるHTMLテーブル構造を持っています:

PRICE       QUANTITY    TOTAL
[5____]     [2____]     10 (TOTAL1=PRICE1*QUANTITY1)

価格と数量の列の値は編集可能です。これらはHTMLフォームフィールドです。

合計列の値は編集できません。代わりに、それらは左側の列の直接の機能です。

テーブルのHTML表現は次のとおりです。

<table id="some_id">
  <tr>
    <td><input type="text" name="price1" value="5" /></td>
    <td><input type="text" name="quantity1" value="2" /></td>
    <td><input type="readonly" name="total1" /></td>
  </tr>
</table>

jQueryを使用して、「total1」の値が常に「price1」に「quantity1」を掛けた値を反映するようにしたいと思います。

質問:これを実現する方法はたくさんあることを理解していますが、jQueryを使用してこれを行うための最もクリーンで最も簡潔な方法は何でしょうか?

「自動更新/派生フィールド」は非常に一般的なjQueryのユースケースであるはずなので、これを実現するためのベストプラクティスの方法がいくつかあると思います。

4

2 に答える 2

1

jQuery計算プラグインjquery.calculation.js )は、この正確な問題を解決します。

次のコードは、jQueryCalculationを使用してこの特定の場合の問題を解決する方法を示しています。

function recalc() {
  $("[name=total1]").calc(  
    "p * q",
    {   
      q: $("input[name=quantity1]"),
      p: $("input[name=price1]")
    },
    function (s) {
      // set number of decimals of resulting value to zero
      return s.toFixed(0);
    },
    function (t) {
      // this runs after the calculation has been completed
    }
  );
}
$("input[name=price1]").bind("keyup", recalc);
$("input[name=quantity1]").bind("keyup", recalc);
recalc();
于 2009-09-24T21:23:45.347 に答える
0

これでうまくいくはずです:

$('input[name^="price"], input[name^="quantity"').keyup(function() {
    $rowTds = $(this).closest('tr').children('td'); // get the row tds
    price = $rowTds.eq(0).children('input').val(); // get the price
    quantity = $rowTds.eq(1).children('input').val(); // get the quantity
    $rowTds.eq(2).children('input').val(price * quantity); // store the value in the total field
});

これはおそらく(関数内で)2行に短縮できますが、これで読みやすくなると思います。

于 2009-09-24T22:23:38.457 に答える