I’m coding a shopping cart type functionality where I am querying a database for a number of items (SKU, qty, name) in an $(.ajax) call. I’d like to display a table with all the items that match what the user is looking for, with the option where the user can specify a quantity desired. They can then click an ‘Add’ to add their selection to a “cart”.
Here’s a simplified example:
<table>
<tr><td>Item A</td><td>SKU: 001</td><td>Qty: <input name="qty-sku001"> <input type="button" value="Add"></td></tr>
<tr><td>Item B</td><td>SKU: 002</td><td>Qty: <input name="qty-sku002"> <input type="button" value="Add"></td></tr>
<tr><td>Item C</td><td>SKU: 003</td><td>Qty: <input name="qty-sku003"> <input type="button" value="Add"></td></tr>
</table>
What is the ideal way to get information from just one row, when it’s button is clicked?
I was thinking of adding an onclick=”AddToCart(x);” to each button, but that’d just pass in an HTML Form Element object. Do I need to make each row it’s own form, or can I get the button’s parent TR and then grab the values from that row’s input and other elements?
The data will end up being appended to a “Cart” div’s table, so I’ll need the three pieces of data I loaded in from my ajax call. I suppose I can add hidden elements to each row, but there must be a more efficient and graceful solution.
Thanks!
assuming that you use jQuery, you can use this:
edit
you can add a class to buttons to prevent running this code for all buttons on your page like this:
and use this javascript: