Bill Gates Bill Gates - 4 months ago 33
PHP Question

woocommerce cart not working properly with jquery

Its my first time that I'm using woocommerce and I'm having some issue on my cart page when I added more than 1 product and increase or decrease any product it will increase quantity of all products.

For example : I've added product a with quantity 2 and product b with quantity 7

if I increase product b to 8 then product a quantity will also increased to 8

Code :

<script>
jQuery('.plus').on('click',function(e){
var val = parseInt(jQuery('input[title="Qty"]').val());

jQuery('input[title="Qty"]').val( val+1 );
});

jQuery('.minus').on('click',function(e){
var val = parseInt(jQuery('input[title="Qty"]').val());
if(val !== 0){

jQuery('input[title="Qty"]').val( val-1 );
} });
</script>


And one more thing price is remains same even if I add increase product or decrease

HTML output : goo.gl/h3w4IQ

Actual cart page : goo.gl/9ynStK

Please let me know why this jQuery code not working and what to do to increase / decrease price also as per product quantity.

Answer

In your jQuery code, you have selected all of the DOMs input while doing plus or minus. You actually needed a specific selector to change only the value of adjacent input. Please replace your code with this one. I have tested it and it works.

jQuery(document).ready(function($) {
    // Attach event on plus
    // We delegate the event to document
    // So that even if there are 100 of plus buttons
    // It would not slow down the page
    $(document).on( 'click', '.plus', function(e) {
        // Get the right element
        var elem = $(this).prev('.qty'),
        // and its value
        val = parseInt( elem.val() );
        // Sanitize the value
        if ( isNaN( val ) ) {
            val = 0;
        }
        if ( val < 0 ) {
            val = 0;
        }
        // Now increase it
        elem.val( ++val ).trigger('change');
    } );

    // Similar appraoch for the minus button
    $(document).on( 'click', '.minus', function(e) {
        // Get the right element
        var elem = $(this).next('.qty'),
        val = parseInt( elem.val() );
        // Sanitize the value
        if ( isNaN( val ) ) {
            val = 0;
        }
        // decrease the value
        val = val - 1;
        // but not a negative
        if ( val < 0 ) {
            val = 0;
        }
        // Set it
        elem.val( val ).trigger('change');
    } );
});
Comments