Change Woocommerce product quantity on a link click with jQuery

On a product details page, I want to have a few buttons to allow the user to select a specific quantity. e.g. 150, 300, 500. When clicked, the quantity input field should update with the value the user clicked on.

I have tried a simple click function, but it's not firing at all - nothing in console either.

<a id="quantity150">150</a>

$('#quantity150').click(function () {
      $('[name="quantity"]').val('150');
      console.log('#quantity150 was clicked');
    });

The quantity input field in Woocommerce has the name= "quantity"

An example of this functionality can be seen here: https://www.anypromo.com/trade-show-events/printed-cards/plastic-wallet-card-p730694 (Quantity table - click and it will change the quantity input field)

Upvotes: 2

Views: 1328

Answers (1)

LoicTheAztec
LoicTheAztec

Reputation: 253784

In Wordpress you need to replace the $ alias by jQuery. Use instead the following:

<a id="quantity150" class="button" href="#">150</a>
<script>
jQuery( function($) {
    $('#quantity150').click( function(e) {
        e.preventDefault();
        $('[name="quantity"]').val('150');
        console.log('#quantity150 was clicked');
    });
});
</script>

Tested an works on WooCommerce single product pages.

Upvotes: 4

Related Questions