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.
- Go to Products → Options and add a text field.
- 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.
- 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
- Code snippet - Itemize the tax in the product options price display
- How to add custom code snippets to your website
- How to only display variation names in the 'Products' option type
- How are product options stored in the WordPress database?
- How does the plugin work with the REST API?
- Can I export product add-ons to my CRM or mailing list?
If searching the knowledge base hasn't answered your question, please contact support.