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!
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;
});
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();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With