2

I'm building off an existing woocommerce wordpress extension, and I'm converting the product variation (size, color etc) dropdown menus into radio boxes. The trickiness is that when a user selects an option from the drop-down list, it triggers something that automatically updates the product inventory and price via ajax.

I used this to convert the inputs into radios (from here):

$('.variations select').each(function(i, select){
    var $select = jQuery(select);
    $select.find('option').each(function(j, option){
        var $option = jQuery(option);
        // Create a radio:
        var $radio = jQuery('<input type="radio" />');
        // Set name and value:
        $radio.attr('name', $select.attr('name')).attr('value', $option.val());
        // Set checked if the option was selected
        if ($option.attr('selected')) $radio.attr('checked', 'checked');
        // Insert radio before select box:
        $select.before($radio);
        $radio.wrap('<div class="vari-option fix" />');
        // Insert a label:
        $radio.before(
          $("<label />").attr('for', $select.attr('name')).text($option.text())
        );
    });

Then I've used this

$(':radio').click(function(){
   $(this).parent().parent().find('label').removeClass('checked');
   $(this).siblings('label').addClass('checked');
   $choice = $(this).attr('value');
   $('.variations select option[value=' + $choice + ']').attr('selected',true);
});

So that when a radio is selected, it mirrors the event on the dropdown option. That works fine, but it's not triggering the refresh of the product info. My guess is there's a difference between changing the 'selected' attribute of a dropdown option and physically clicking on the same option. Any guess at what event might be triggering that ajax function that I'm not taking into account? And a solution that ideally doesn't involve modifying woocommerce's original code? I've tried using .click() on the select option but it made no difference.

Community
  • 1
  • 1
essmahr
  • 676
  • 4
  • 15

1 Answers1

3

Programmatically changing the value of an element doesn't trigger the change event, and I would assume that programmatically setting the selected attribute/property on an <option> also wouldn't trigger the change event on the containing <select> element.

Fortunately, you can easily trigger that event programmatically using jQuery:

$('.variations select option[value=' + $choice + ']').attr('selected',true).parent().trigger('change');

The .parent() call returns a jQuery object containing the <select> element, then .trigger('change') triggers any event handlers bound to the change event on that object.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76