HELP regarding shopping cart (JQUERY)

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

Hi !

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.

Hope this helps !

i have thought for same . but it will require to assign every button a different id ? so to know which element was clicked

Yes. Up to me is the simple way using a unique Id for each of articles.

Where do you get these article from?

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 :slight_smile:

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.

1 Like