• Resolved Jonas Marlo L?rken

    (@iamjonasmarlo)


    Hey all! I would like to change the variant of a product using JavaScript. To do this, I change the value of the corresponding select field and then trigger the change.

    $('.variations input').change(function() {
        let value = $(this).val();
        $(this).parents('.variations').find('select').val(value);
    
        $('.variations select').trigger('change');
    });

    The value of the select fields also changes, however Woocommerce does not seem to register the change as I cannot add the product to the cart. Only when I manually selected a value again via the select fields, this seems to work.

    Do I need to notify another element about the change?

Viewing 3 replies - 1 through 3 (of 3 total)
  • Plugin Support Kaushik S. a11n

    (@kaushiksomaiya)

    Hi there @iamjonasmarlo,

    Thank you for contacting us!

    I understand you’d like to change the variation using JS. That’s an interesting question.

    On my test site on Storefront theme, the following line of code works:

    jQuery("#size").val('Long').change();

    Note that the val() is case-sensitive.

    It would be great if you could share your product URL to have a look and also explain what should trigger the change in variation.

    Thread Starter Jonas Marlo L?rken

    (@iamjonasmarlo)

    Hey @kaushiksomaiya

    thanks a lot for your answer. Unfortunately, it doesn’t seem to be working. When a button is pressed, the value in the select field changes, but I can’t add the product to the cart because the value of the input field (variation_id) doesn’t change.

    https://senkelfabrik.dev-psm.de/produkte/test2/

    $('.variations input').change(function() {
        let value = $(this).val();
        $(this).parents('.variations').find('select').val(value).change();
    });
    Plugin Support Kaushik S. a11n

    (@kaushiksomaiya)

    Hi there @iamjonasmarlo

    The code below appears to be working for me on your page:

    
    jQuery('.variations input').change(function() {
        var value = jQuery(this).val();
        jQuery(this).closest('.variations').find('select').val(value).change();
    });
    

    Be sure to add this in document ready as explained here: https://learn.jquery.com/using-jquery-core/document-ready/

    I hope this helps! ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Change variation of product with JavaScript’ is closed to new replies.