1. Home
  2. Knowledge Base
  3. WooCommerce Product Options
  4. Advanced Usage

Code snippet: Display a product option based on the quantity selected

The conditional logic in WooCommerce Product Options lets you show/hide product options based on which other variations and options the customer selects. However, it doesn't let you show/hide options based on the quantity that the customer has selected.

The following code snippet allows you to do this. Please note that it is aimed at developers and if you don't know how to use it, please refer to our article about code snippets or use our customization service. This example assumes that you want to display a text field when a quantity of 250 or more is selected.

  1. Go to Products → Options and add a text field.
  2. In the advanced settings for your text field, add the following CSS classes:wpo-field-hide wpo-optional-250-text
    • wpo-field-hide will hide the text field from the front end of your site when the page first loads.
    • wpo-optional-250-text will display the text field when a quantity of 250 or more is selected.
  3. Add the following code snippet to your site:
document.querySelector( 'form.cart input.qty' ).addEventListener( 'change', ( event ) => {
    const field = document.querySelector( 'div.wpo-optional-250-text' );
    if ( ! field ) {
        return;
    }

    const qty = parseInt( event?.target?.value ?? 1 );
    field?.classList?.toggle( 'wpo-field-hide', qty < 250 );

    // optionally, you can also set the field as required if you need to
    // field.querySelector( 'input' ).required = qty >= 250
} );

Related Articles

If searching the knowledge base hasn't answered your question, please contact support.