I am facing problem in Add to cart button in my Website.(I am using Codeigniter Shopping Cart)
For now I am having button which is in the form. When I click add to Cart button, my product is added into the cart.
But I want something like - when I click add to cart button for first time its value should change to Remove product calling some method having Add function.
Similarly when I click on Same button with value Remove Product it should call other method having remove code and its value should change to Add to Cart.
I am having code in Javascript and AJAX,but I don't know how to call two different method using same button.
Below is the Code I tried.
<script>
instance.addCart.on('click', function(e){
e.preventDefault();
var self = $(this);
if (self.hasClass('btn-primary')){
self.removeClass('btn-primary').addClass('btn-default').text('Remove');
} else {
self.removeClass('btn-default').addClass('btn-primary').text('Add to Cart');
}
});
</script>
<a href="#" class="btn btn-primary add-cart">Add to Cart</a>
I Know how to send data and call particular method in AJAX.
This is pretty Confusing. Please Help
Just put the different functions in the if/else
statement blocks?
if (self.hasClass('btn-primary'))
{
self.removeClass('btn-primary').addClass('btn-default').text('Remove');
addToCart();
}
else
{
self.removeClass('btn-default').addClass('btn-primary').text('Add to Cart');
removeFromCart();
}
You can try this :
JS code:
$('.btn_add_remove_cart').click(function(e){
e.preventDefault();
var self = $(this);
if (self.hasClass('add-cart')){
// if it's add cart button, replace add-cart class by remove-cart and change label
self.removeClass('add-cart').addClass('remove-cart').text('Remove');
} else {
// it's remove cart button, do the inverse
self.removeClass('remove-cart').addClass('add-cart').text('Add to Cart');
}
});
HTML code:
I added a new class btn_add_remove_cart
just for jquery calls :
<a href="#" class="btn btn-primary add-cart btn_add_remove_cart">Add to Cart</a>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.