Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find input fields in current table row with class

Tags:

jquery

forms

I am making a book shop and want to add a fancy jQuery order form. The point is that the user shall choose the quantity of a book with a minus and plus button and then let JavaScript calculate a total sum for that book.

I have a markup as follows:

  <tr>
    <td><p>Book title</p></td>
    <td><p><a href="#" class="bookDecrement">-</a><input type="text" class="bookQuantity disabled" disabled /><a href="#" class="bookIncrement">+</a></p></td>
    <td><p><input type="text" class="bookPrice disabled" value="70" disabled /></p></td>
    <td><p>=</p></td>
    <td><p><input type="text" class="bookTotal disabled" disabled /></p></td>
  </tr>

How do I reach the bookPrice and bookTotal class in this row with jQuery? Since I have multiple book titles I need to only access the input filed in the current row.

Thanks!

like image 300
Fred Bergman Avatar asked Jan 30 '10 21:01

Fred Bergman


2 Answers

This should do it:

$('.bookDecrement, .bookIncrement').click(function() {

    // Get the current row
    var row = $(this).closest('tr');

    // Determine if we're adding or removing
    var increment = $(this).hasClass('bookDecrement') ? -1 : 1;

    // Get the current quantity
    var quantity = parseInt(row.find('.bookQuantity').val(), 10);
    // Adjust the quantity
    quantity += increment;
    // Quantity must be at least 0
    quantity = quantity < 0 ? 0 : quantity;

    // Get the price
    var price = parseFloat(row.find('.bookPrice').val());

    // Adjust the total
    row.find('.bookTotal').val(quantity * price);

    // Return false to prevent the link from redirecting to '#'
    return false;
});
like image 100
Tatu Ulmanen Avatar answered Sep 24 '22 15:09

Tatu Ulmanen


You can get to the ancestor tr and descend again to the input within. Like this:

$("a.bookIncrement").click(function() {
    $(this).closest("tr").find("input.bookPrice").doSomething();
});
like image 43
Chetan S Avatar answered Sep 21 '22 15:09

Chetan S