WooCommerce Attributes Validation using jQuery

Viewed 113

On Variable product page when you click on Add to Cart without selecting any attribute it will show you an alert like this

Default alert message

So instead of this alert I wanted to show a message that a particular attribute is not selected or a group of attribute is not selected.

For example,

  1. If color is not selected then it should show Please select a color.
  2. If color and size are not selected then it should show Please select a color and size.

I have tried a workaround to achieve with jQuery

$('.single_add_to_cart_button').on('click', function (e) {
    if ($(this).is('.disabled')) {
        e.preventDefault();

        if ($(this).is('.wc-variation-selection-needed')) {

            var empty_variations = [];

            $('form.variations_form.cart').find('table.variations tr').each(function( index ) {
                var $variation_label = $(this).find('td.label');
                var $variation_value = $(this).find('td.value');

                var $variation_dd = $('select', $variation_value);
               
                if( $variation_dd.val() == '' || $variation_dd.val() == null ){
                    var label_text = $('label', $variation_label).text();
                    empty_variations.push( label_text )
                }

            });
            
            if( empty_variations.length != 0 ){
                alert( 'Please select ' + empty_variations.join(', ') + '.'); 
                return false;
            }            
        }
    }   
});

However anyone can let me know a standard way to implement this.

Thanks!

0 Answers
Related