Categories: javascript, php, jquery

Input fields with incrementing buttons Jquery not working properly

1 answer

I have a A plus minus and a input button. Input starts at 1 and if you click on + button it has to add +1 and if you click - it decreseas 1. Now I have this html div 35x:

35x same div because there are 35 products each product has a +/- button. The crazy thing is if I click + with this code it adds up 35 (counts products), I just want the clicked one to increase with 1. What am I doing wrong?

jQuery( function( $ ) {             if ( ! String.prototype.getDecimals ) {                 String.prototype.getDecimals = function() {                     var num = this,                         match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);                     if ( ! match ) {                         return 0;                     }                     return Math.max( 0, ( match[1] ? match[1].length : 0 ) - ( match[2] ? +match[2] : 0 ) );                 }             }             // Quantity "plus" and "minus" buttons             $( document.body ).on( 'click', '.plus, .minus', function() {                 var $qty        = $( this ).closest( '.quantity' ).find( '.qty'),                     currentVal  = parseFloat( $qty.val() ),                     max         = parseFloat( $qty.attr( 'max' ) ),                     min         = parseFloat( $qty.attr( 'min' ) ),                     step        = $qty.attr( 'step' );                  // Format values                 if ( ! currentVal || currentVal === '' || currentVal === 'NaN' ) currentVal = 0;                 if ( max === '' || max === 'NaN' ) max = '';                 if ( min === '' || min === 'NaN' ) min = 0;                 if ( step === 'any' || step === '' || step === undefined || parseFloat( step ) === 'NaN' ) step = 1;                  // Change the value                 if ( $( this ).is( '.plus' ) ) {                     if ( max && ( currentVal >= max ) ) {                         $qty.val( max );                     } else {                         $qty.val( ( currentVal + parseFloat( step )).toFixed( step.getDecimals() ) );                     }                 } else {                     if ( min && ( currentVal <= min ) ) {                         $qty.val( min );                     } else if ( currentVal > 0 ) {                         $qty.val( ( currentVal - parseFloat( step )).toFixed( step.getDecimals() ) );                     }                 }                  // Trigger change event                 $qty.trigger( 'change' );             });         }); 

PHP:

/**  * Adjust the quantity input values  */ add_filter( 'woocommerce_loop_add_to_cart_link', 'quantity_inputs_for_loop_ajax_add_to_cart', 10, 2 ); function quantity_inputs_for_loop_ajax_add_to_cart( $html, $product ) {     if ( $product && $product->is_type( 'simple' ) && $product->is_purchasable() && $product->is_in_stock() && ! $product->is_sold_individually() ) {         // Get the necessary classes         $class = implode( ' ', array_filter( array(             'button',             'product_type_' . $product->get_type(),             $product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',             $product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',         ) ) );          // Adding embeding <form> tag and the quantity field         $html = sprintf( '%s%s<a rel="nofollow" href="%s" data-quantity="%s" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>%s',             '<form class="cart">',             woocommerce_quantity_input( array(), $product, false ),             esc_url( $product->add_to_cart_url() ),             esc_attr( isset( $quantity ) ? $quantity : 1 ),             esc_attr( $product->get_id() ),             esc_attr( $product->get_sku() ),             esc_attr( isset( $class ) ? $class : 'button' ),             $product->add_to_cart_text(),             '</form>'         );     }     return $html; } 

All answers to this question, which has the identifier 61232120

The best answer:

You seem to have over complicated this. You can achieve what you need by using jQuery's DOM traversal methods to amend the input related to the clicked button:

$('.amend').on('click', function() {    $(this).siblings('.qty').val((i, v) => parseInt(v, 10) + $(this).data('inc'));  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <div class="quantity">    <button class="amend" type="button" data-inc="-1">-</button>    <input type="number" step="1" min="0" name="quantity" value="1" title="Aantal" class="input-text qty text" size="4">    <button class="amend" type="button" data-inc="1">+</button>  </div>  <div class="quantity">    <button class="amend" type="button" data-inc="-1">-</button>    <input type="number" step="1" min="0" name="quantity" value="1" title="Aantal" class="input-text qty text" size="4">    <button class="amend" type="button" data-inc="1">+</button>  </div>  <div class="quantity">    <button class="amend" type="button" data-inc="-1">-</button>    <input type="number" step="1" min="0" name="quantity" value="1" title="Aantal" class="input-text qty text" size="4">    <button class="amend" type="button" data-inc="1">+</button>  </div>

Last questions

how do i remove the switch on my home screen?
how to edit the JS date and time to update atuomatically?
How to utilize data stored in a multidimensional array
Powermockito not mocking URL constructor in URI.toURL() method
Android Bluetooth LE Scanner only scans when phone's Location is turned on in some devices
docker wordpress container can't connect to mysql container
How can I declare a number in java that is more than 64-bits? [duplicate]
Optaplanner solutionClass entityCollectionProperty should never return null error when simple JSON object passed to controller
Anylogic, get the time a pedestrain is in a queue
How do I fix this syntax issue with my .flex file?
Optimizing query in PHP
How to find the highest number of a column and print two columns of that row in R?
Ideas on “Error: Type com.google.firebase.iid.zzav is referenced as an interface from com.google.firebase.messaging.zzd”?
JCIFS SmbFile.exists() and SmbFile.isDirectory() return false when it exists and I can listFiles()
PHP total order
Laravel booking system design
neural net - undefined column selected
How to indicate y axis does not start from 0 in ggplot?
Fragments in backStack
Spinner how to change the data