jQuery: modificare la quantità di un prodotto in un carrello di WooCommerce

Con jQuery possiamo facilmente modificare la quantità di un prodotto in un carrello di WooCommerce. Vediamo come fare.

Partiamo dal seguente form personalizzato di WooCommerce:


<form action="http://sito/cart/?add-to-cart=1234" method="post" class="shop-cart" enctype="multipart/form-data">
	<div>
		<input type="hidden" name="quantity" value="1" class="cart-qty" />
		<button type="submit" class="button">Aggiungi al carrello</button>
	</div>
	<div class="shop-cart-qty-actions">
		<a href="" class="increase-qty">+</a>
		<span class="qty-count">1</span>
		<a href="" class="decrease-qty">-</a>
	</div>
</form>

Possiamo definire il seguente codice jQuery:


$( ".shop-cart" ).each(function() {
	var $form = $( this ),
		$qty = $( ".cart-qty", $form ),
		$increase = $( ".increase-qty", $form ),
		$decrease = $( ".decrease-qty", $form ),
		$count = $( ".qty-count", $form ),
		qty = 1;
		
		$increase.on( "click", function( e ) {
			e.preventDefault();
			qty++;
			$qty.val( qty );
			$count.text( qty );
			
		});
		
		$decrease.on( "click", function( e ) {
			e.preventDefault();
			qty--;
			
			if( qty == 0 ) {
				qty = 1;
			}
			
			$qty.val( qty );
			$count.text( qty );
			
		});
	
});

Torna su