views:

583

answers:

4

I want add a key up event to every text box element in a table excluding the last text box in each row. The table is dynamic on both axis.

The key up event will total the values in all but the last text box. The total is then placed in the last text box for the row.

The script for the totaling and setting the total all works fine.

I tired the following to select the target elements:

$("#Grid tr input:text:not(:last)").keyup(function(){
    //do total stuff here
})

Unfortunately it works as documented and not as I wanted and selects all but the very last checkbox.

Ideally the solution will not involve any further markup to the table example below or involve any looping. However if that is what it takes, so be it.

<table id="Grid">
 <tr id="r1">
  <td>Row 1</td>
  <td><input type="text" id="txt_a1_b1"></td>
  <td><input type="text" id="txt_a1_b2"></td>
  <td><input type="text" id="txt_a1_b3"></td>
  <td><input type="text" id="txt_a1_b4"></td>
  <td><input type="text" id="total_a1"></td>
 </tr>
 <tr id="r2">
  <td>Row 2</td>
  <td><input type="text" id="txt_a2_b1"></td>
  <td><input type="text" id="txt_a2_b2"></td>
  <td><input type="text" id="txt_a2_b3"></td>
  <td><input type="text" id="txt_a2_b4"></td>
  <td><input type="text" id="total_a2"></td>
 </tr>
 <tr id="r3">
  <td>Row 3</td>
  <td><input type="text" id="txt_a3_b1"></td>
  <td><input type="text" id="txt_a3_b2"></td>
  <td><input type="text" id="txt_a3_b3"></td>
  <td><input type="text" id="txt_a3_b4"></td>
  <td><input type="text" id="total_a3"></td>
 </tr>
</table>

One final point, the total text box does need to be a text box as there is also a requirement to enter a total then split it across the row and I do not want a key up function in the total text box.

A: 

If you want to do it all in one shot, use :last-child:

... $('table tr input:not(:last-child)') ...

From the documentation: "While :last matches only a single element, this matches more than one, one for each parent."

John Feminella
This one selects whole TD not INPUTs
Tomasz Tybulewicz
Whoops, good catch. Thanks.
John Feminella
This is also incorrect. It won't actually select any inputs as they're all last children.
cletus
A: 

I would use the each function on the rows and find all but the last input in each row.

$('#Grid > tr').each( function() {
    $(this).find('input:not(:last)).keyup( ... )
});
tvanfosson
A: 

This one finds all inputs (exept last one) in all TRs

$("#Grid tr").find("input:text:not(:last)")
Tomasz Tybulewicz
+2  A: 

I'm surprised noones quite got this yet:

$("#Grid tr :not(:last-child) :text").keyup(function(){
    //do total stuff here
})
cletus