On a recent project, I wrote a plugin that creates product grids, and restricts customers from buying certain products in single – they must buy in a pack. For those, we used drop-down menus (selects menus), so and stepped them by the number in the pack. For example, one item requires that they buy 6, so the menu has 6, 12, 24, etc. all the way up the total quantity available. Another may require 12, so it shows a menu with 12, 24, 36, 3tc.

When we got to the shopping cart, we had to create a WooCommerce template for cart.php and create logic to ensure that they couldn’t change quantities in the cart – and would be required to still order in pack quantities. However, in the cart, when the “Update Cart” is clicked, it uses ajax to update the cart. So, we took advantage of the ajax call to run our javascript to select the menu option for the correct quantity, etc.

The problem with using jquery without tying into the ajax was that when the cart was loaded via ajax, the number was off. So, we tied into updated_carts_total, and when the “Update cart” button is clicked, our jquery code is run, ensuring the menu has the correct option selected. Here’s the jquery function we built and put in our .js file. We then called the function from our select menu.

function cartpackqty(itemValue) {
	var itemValue = itemValue;
	$('select.stepped_dropdown.vg_quantity.select.qty').on('change', function() {
		var newQty = this.value;
		$( document.body ).on( 'updated_cart_totals', function (){
			document.getElementById(newQty).selected = true;
			var newQty = newQty;
		});
	});
}