i am building a shopping cart website. the landing page has many items showing and a button is attached with each item. i want that if user clicks on the button associated with that item .the respective item gets added . how can i bind this logic via jquery.
in short how do i select that specific item with the button attached to it . what logic shall i apply for this type of binding
Assign a specific identifier such an id or data attribute to your βAdd to Cardβ button with a unique value for that items. And listen a click event on each βAdd to Cardβ button in JQuery. Whenever a visitor or user clicks βAdd to Cardβ get its id or data attribute value and store it. In this way, you will know exactly which items to add in the Visitor or User 's Shop Card.
Yeah I think assigning unique information to each item is the way to go. You will need to know which element was clicked but also itβs important meta data too.
There are probably a million different ways to do it, but the simplest would be to just assign an ID to each item (for metadata) and grab the inner text of the item and do something like this ( https://jsfiddle.net/xpvt214o/387438/ ) . This is a very simple mock up, let me know if you need additional help
var cartItems = [];
$('.items').on('click', '.item', function(e) {
$('#cart-item').html('');
// e.target is the clicked element
cartItems.push(e.target.innerText);
cartItems.forEach(function(item) {
$('#cart-item').append('<li>' + item + '</li>');
});
})
Ideally your dataset would come from the server / .json file somewhere. And therefore you could use a similar forEach loop to generate the HTML for all the available cart items. Then you could generate unique IDβs as well as any other metadata, like items in stock, price, etc
Furthermore, you could reduce the cartItems array to an object so that the quantities are added together instead of the list growing longer and longer.