Reputation: 129
My problem is fairly basic (at least, for you guys), but I can't seem to get it work.
So I have products and an add to cart button. I need it so that whenever I add a product already in the cart, it will not add it in a new line, but rather, just increase the count.
Somehow, it only recognizes the first product that was clicked. Here is my fiddle:
var initial = 0;
jQuery('.add-to-cart').live('click', function() {
jQuery('.no-prods').fadeOut();
jQuery('.subtotal').fadeIn();
var dataOwner = jQuery(this).parent().closest('div').attr('data-owner');
var dataClass = jQuery(this).parent().closest('div').attr('data-owner');
dataClass = '.' + dataClass;
var count = '<span class="prod-count ' + dataOwner + '">' + 1 + '</span>';
var price = jQuery(this).parent().closest('div').attr('data-price');
price = 'jQuery<span class="prod-price">' + price + '</span>';
if(initial == 0) {
var p_name = jQuery('.span9 ' + dataClass + ' h3').clone();
var p_name_and_quantity = jQuery(p_name).after(' ' + count + ' x ' + price);
jQuery('.my-cart').append(p_name_and_quantity);
initial = 1;
//get_subtotal();
} else {
get_products(dataClass, count, price);
}
});
function get_products(dataClass, count, price) {
jQuery('.my-cart h3').each(function() {
var c_name = jQuery(this).html();
var product = jQuery('.span9 ' + dataClass + ' h3').html();
if(c_name == product) {
//get_count(count, dataClass);
return false;
} else {
var this_p_name = jQuery('.span9 ' + dataClass + ' h3').clone();
var this_p_name_and_quantity = jQuery(this_p_name).after(' ' + count + ' x ' + price);
jQuery('.my-cart').append(this_p_name_and_quantity);
get_subtotal();
}
});
return false;
}
Upvotes: 0
Views: 101
Reputation: 3395
Well I have updated your code and made it in my own way:- Fiddle
function get_products(el) {
if(products.indexOf($(el).attr('data-product')) == -1){
products.push($(el).attr('data-product'))
$('.my-cart').append('<h3 class="product">' + $(el).parent().find("h3").html() + '</h3>');
}
subTotal += +$(el).parent().attr("data-price");
$(".subtotal").html("Subtotal: $" + subTotal);
}
Hope this is what you are looking for.
Upvotes: 1