Find input fields in current table row with class

forms, jquery

Solution

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;
});

Problem

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!

Original source