简体   繁体   中英

Increment Cart Quantity with javascript(rails)

I need to be able to have the correct quantity in my cart, but the reason I'm using js is because we have assemblies from vehicles with all the products listed but some are on there twice so it currently is taking the bottom most quantity when both fields are set to a certain number, instead of adding them together. And of course both parts ids are the same adding to the issue as well. Here is what I have so far:

$('#add_to_cart').submit(function(){
    arr1 =  jQuery.makeArray($('input[id*="myap_"]'));
    arr2 = jQuery.makeArray($('input[id*="products_"]'));
    fields = arr1.concat(arr2).sort();
    jQuery.each(fields, function(index, domEle){
      if (index > 0 && $(this).attr('id') == fields[index-1].id){
        curr_val = ($.isNumeric(domEle.value)) ? parseInt(domEle.value) : 0
        second_val = ($.isNumeric(fields[index-1].value)) ? parseInt(fields[index-1].value) : 0
        domEle.value = curr_val + second_val;
        fields[index-1].value = 0;
    }
    });
});

we have to different kinds of products on the same page so that is why there is myap and products. Also, this seems to work sometimes but not always and generally not in ie.

Figured it out. It wasn't sorting correctly. Needed this:

fields = arr1.concat(arr2).sort(function(a,b){return a.id > b.id ? 1 : -1;});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM