1

I would like to have a single button that does 2 functions without having to refresh or visit another page. 1. First will be Add to Cart button when clicked it will add a product to a cart and once the product is added to cart the button should 2. change to Remove from cart and when clicked Remove from cart button it should remove the item from cart and again change the button again back to Add to cart.

Right now I am using very simple onclick event button

<button class="btn btn-sm btn-inverse btn-embossed" onclick="ajaxSubmit('/add/product/<?php echo $productId; ?>/"><span><?php echo $this->__('Add to Cart') ?></span></button>

Product can be removed with url below

/remove/product/<?php echo $productId ?>/

I have already tried several options from other forums but I couldn't achieve it.

2
  • Can you show us what you have tried? Commented Jan 29, 2016 at 9:32
  • The easiest way is to use two buttons and hide one. See stackoverflow.com/questions/8685107/… for details how to hide a button. Commented Jan 29, 2016 at 9:47

1 Answer 1

1

I suggest you to move your ajax call from onclick event so you don't need o duplicate long code. Second add parameters like current action and id to data for jQuery access.

$('.product-btn').click(function(){
	if($(this).attr('data-action')=="add"){
  	  ajaxSubmit('/add/product/'+$(this).attr('data-id')+'/');
          $(this).attr('data-action','remove');
          $(this).children('span').html('Remove from cart');
  }else{
  	ajaxSubmit('/remove/product/'+$(this).attr('data-id')+'/');
        $(this).attr('data-action','add');
        $(this).children('span').html('Add to cart');
  }
});
<button class="btn btn-sm btn-inverse btn-embossed product-btn" data-action="add" data-id="<?php echo $productId; ?>"><span><?php echo $this->__('Add to Cart') ?></span></button>

Sign up to request clarification or add additional context in comments.

2 Comments

I think jQuery is causing conflict as I am getting Uncaught TypeError: Cannot read property 'click' of null error
I am getting Uncaught ReferenceError: ajaxSubmit is not defined error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.