A simple shopping Cart for self learning

For the sake of my learning, I am trying to build simple shopping cart →

This is the simple and whole script that I was able to write →

var itemCount = 0;
var priceTotal = 0;

// Add Item to Cart
$('.add').click(function () {
	itemCount++;

	$('#itemCount').text(itemCount).css('display', 'block');
	$(this).siblings().clone().appendTo('#cartItems').append('<button class="removeItem">Remove Item</button>');

	// Calculate Total Price
	var price = parseInt($(this).siblings().find('.price').text());
	priceTotal += price;
	$('#cartTotal').text("Total: €" + priceTotal);
	console.log('price');

});


// Remove Item From Cart
$('#shoppingCart').on('click', '.removeItem', function(){
$(this).parent().remove();
itemCount --;
$('#itemCount').text(itemCount);

	// Remove Cost of Deleted Item from Total Price
	var price = parseInt($(this).siblings().find('.price').text());
	priceTotal -= price;
	$('#cartTotal').text("Total: €" + priceTotal);

	if (itemCount == 0) {
		$('#itemCount').css('display', 'none');
	}
});

But in this remove item script is not working →

	// Remove Cost of Deleted Item from Total Price
	var price = parseInt($(this).siblings().find('.price').text());
	priceTotal -= price;
	$('#cartTotal').text("Total: €" + priceTotal);

	if (itemCount == 0) {
		$('#itemCount').css('display', 'none');
	}

Define ‘is not working’. Such terms are meaningless to us.

When you delete the added Item it doesn’t reduces the Price.

Well… if you’ve deleted the parent from the DOM… then… is it going to find anything?

What happens if you move the removal line down to the end?

$(this).parent().remove();
var price = parseInt($(this).siblings().find('.price').text());

I think both are binded to one event and they are occurring simultaneously.

Lines of code do not occur simultaneously.

var x = 1

$('btn').click(function() {
  x = 3
  print(x)
}

will print 3.

var x = 1

$('btn').click(function() {
  print(x)
  x = 3
}

Will print 1 (the first time, anyway.).

It looked like there was some hosting co. propagation(or cache) issue. The same code and it is deleting the added item and same time recalculating(or subtracting the price) now.

Ok, but in my case sir. The code is working.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.