Select custom with conflicting script

Asked

Viewed 33 times

0

So I have a script to change the default select of Woocommerce variations, so far so good, the problem is when a variation is out of stock, the custom select should have the same options as the default select.

"Select" custom above, standard below. White and P are out of stock.

"Select" personalizado acima, padrão abaixo. Branco e P estão fora de estoque.

I found that the script Variations JS of Woocommerce removes out-of-stock options programmatically, but as my script runs after the Woocommerce script I thought it should work. I even managed to make it work by adding a 2000ms setTimeout, but it’s too long and actually breaks other functions I have. I’d be grateful if someone knew how to fix it.

$('.variations select').each(function(){
    var select = $(this);
    var div = $('<div class="grupo-atributos">');
    var ul = $('<ul>');
    select.parent('.value').siblings('.label').find('label').each(function(){
      var label = $(this).text();
      div.append('<span>'+label+'</span>');
    });

    $('#custom-select-produto-variavel').append(div);
    div.append(ul);

    select.find('option').each(function(){
      var titulo = $(this).text();
      var data_value = $(this).val();
      ul.append('<li data-value='+data_value+'>'+titulo+'</li>');
    
    select.change(function(){
    select.find('option:selected').each(function(){
      var opcao_selected = $(this);
      select.find('option:not(:selected)').each(function(){
        var opcao_not_selected = $(this);
        $('#custom-select-produto-variavel li').each(function(){
          var opcao_custom = $(this);
          if(opcao_custom.attr('data-value')==opcao_selected.val())
              opcao_custom.addClass('atributo-selected');
          if(opcao_custom.attr('data-value')==opcao_not_selected.val())
              opcao_custom.removeClass('atributo-selected');
        });
      });
    });
    }).change();

    });
  });

  $('#custom-select-produto-variavel div ul li:contains("Escolha uma opção")').remove();

  $('#custom-select-produto-variavel ul li').click(function() {
    var novoVal = $(this).data('value');
    $('.variations select:has([value='+novoVal+'])').val(novoVal);
    $('.variations select').trigger('change');
  });
<div id="custom-select-produto-variavel"></div>

  • Try putting the code inside a $(window).on("load", function(){ CÓDIGO AQUI });

  • I had tried, it doesn’t work, it’s like Variations JS keeps running after the page loads, very strange.

  • You can do some Gambi with setInterval, but I don’t think it’s worth it.

1 answer

0


I found that the default select has a delay of 100 ms to start, so to make my script work properly, I needed to add these lines.

$(document).ready(function(){
setTimeout(function(){
 // Meu script
}, 150);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.