views:

600

answers:

2

I have an HTML table structure that looks something along the lines of:

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

The values in the price and quantity column are editable. These are HTML form fields.

The values in the total column are not editable. Instead they are direct functions of the columns to the left.

The HTML representation of the table is:

<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>

Using jQuery I'd like to make it so that the value of "total1" always reflects the value of "price1" times "quantity1".

Question: I understand that there are numerous way to achieve this - but what would be the cleanest most concise way to do it using jQuery?

Since "auto-updating/derived fields" should be a quite common jQuery use-case I would assume that there exists some best practice method to achieve this.

+1  A: 

The jQuery Calculation plugin (jquery.calculation.js) solves this exact problem.

The following code shows how to use jQuery Calculation to solve the problem in this particular case:

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();
knorv
A: 

This should do the trick:

$('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
});

This could probably be shortened into 2 lines (inside the function), but I think this keeps it readable.

Darryl Hein