Advertisement
BackuPs-nl

Woocommerce Quantity Spinners Update

Nov 16th, 2018
241
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.88 KB | None | 0 0
  1. jQuery( function( $ ) {
  2.  
  3.     if ( ! String.prototype.getDecimals ) {
  4.         String.prototype.getDecimals = function() {
  5.             var num = this,
  6.                 match = ('' + num).match(/(?:\.(\d+))?(?:[eE]([+-]?\d+))?$/);
  7.             if ( ! match ) {
  8.                 return 0;
  9.             }
  10.             return Math.max( 0, ( match[1] ? match[1].length : 0 ) - ( match[2] ? +match[2] : 0 ) );
  11.         }
  12.     }
  13.  
  14.     function wcqi_refresh_quantity_increments(){
  15.         $( 'div.quantity:not(.buttons_added), td.quantity:not(.buttons_added)' ).addClass( 'buttons_added' ).append( '<input type="button" value="+" class="plus" />' ).prepend( '<input type="button" value="-" class="minus" />' );
  16.     }
  17.  
  18.     $( document ).on( 'updated_wc_div', function() {
  19.         wcqi_refresh_quantity_increments();
  20.     } );
  21.  
  22.     $( document ).on( 'cart_page_refreshed', function() {
  23.         wcqi_refresh_quantity_increments();
  24.     });
  25.  
  26.     $( document ).on( 'click', '.plus, .minus', function() {
  27.         // Get values
  28.         var $qty        = $( this ).closest( '.quantity' ).find( '.qty'),
  29.             currentVal  = parseFloat( $qty.val() ),
  30.             max         = parseFloat( $qty.attr( 'max' ) ),
  31.             min         = parseFloat( $qty.attr( 'min' ) ),
  32.             step        = $qty.attr( 'step' );
  33.  
  34.         // Format values
  35.         if ( ! currentVal || currentVal === '' || currentVal === 'NaN' ) currentVal = 0;
  36.         if ( max === '' || max === 'NaN' ) max = '';
  37.         if ( min === '' || min === 'NaN' ) min = 0;
  38.         if ( step === 'any' || step === '' || step === undefined || parseFloat( step ) === 'NaN' ) step = 1;
  39.  
  40.         // Change the value
  41.         if ( $( this ).is( '.plus' ) ) {
  42.             if ( max && ( currentVal >= max ) ) {
  43.                 $qty.val( max );
  44.             } else {
  45.                 $qty.val( ( currentVal + parseFloat( step )).toFixed( step.getDecimals() ) );
  46.             }
  47.         } else {
  48.             if ( min && ( currentVal <= min ) ) {
  49.                 $qty.val( min );
  50.             } else if ( currentVal > 0 ) {
  51.                 $qty.val( ( currentVal - parseFloat( step )).toFixed( step.getDecimals() ) );
  52.             }
  53.         }
  54.  
  55.         // Trigger change event
  56.         $qty.trigger( 'change' );
  57.     });
  58.  
  59.     wcqi_refresh_quantity_increments();
  60. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement