Question

I have a problem in product listing quantity counter, sometimes it will work and sometimes it will not. I want to create custom JQuery script to enable product counter increment and decrement, But the problem is that, it is a listing page so if I create script others will be affected. Please correct me if I'm wrong.

Below attached is screenshot.

enter image description here

Here's my script that is working in product detail page only.

 var $currentQTY=parseInt($('#qty').val());

    $(".qty-inc").click(function(){
        $currentQTY=$currentQTY+1;
        $('#qty').val($currentQTY);
        // console.log($currentQTY);
    });

    $(".qty-dec").click(function(){
        $currentQTY=$currentQTY-1;
        if ($currentQTY<1){
            $currentQTY=0;
        }
        $('#qty').val($currentQTY);
        // console.log($currentQTY);
    });

Thanks

Was it helpful?

Solution 2

Here's how I solved my problem.

This is the codes.

enter image description here

OTHER TIPS

Others get affected because id of each input box is same.

You can achieve whatever you want by doing following -

You will have to define each input box with different-2 id and give a common class name for each input box (.qty).

For example -

Input boxes id will be like - #qty_1, #qty_2

Class name will be like - .qty

Note - Suffix in the input box id can be the product id of the respective product.

Then put both increment and decrement buttons and input box in the same division (By doing this you can easily find the respective input box). Then you can use the object of clicked element (this) in the function to identify the clicked element.

Assuming that your structure of division is something like following -

<div>
<input class="qty" id="qty_1" />
<button class="qty-inc">+</button>
<button class="qty-dec">-</button>
</div>

Javascript code Example -

$(".qty-inc").click(function() {
   // This will return the quantity of the box which is clicked
  // this is the object of element, which has been clicked
   var currentQTY = parseInt($(this).parent().find(".qty").val());
   // Increasing the quantity
   currentQTY = currentQTY + 1;
   // Setting the quantity of only that element,
   //which has been clicked
   $(this).parent().find(".qty").val(currentQTY);
});

You can do the same with .qty-dec , make sure to remove

var currentQTY=parseInt($('#qty').val());

line as the replacement of that line is included inside the click function.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top