Skip to content Skip to sidebar Skip to footer

How To Hide And Auto Select Option Using Data-attributes?

I have three dropdowns. I want 2 functionality in the below code. Hide .variant-selector option if it is not available in name='id' dropdown. Also I want to auto select name='id'

Solution 1:

You don't need toLowerCase() also instead of option:contains it's better to use option[value]

Try this:

$(document).ready(function() {
  $('.variant-selector').change(function() {
    const val = this.value;
    const variant_type = this.dataset.type;
    const other_type = $('.variant-selector:not([data-type="' + variant_type + '"])')[0].dataset.type;

    $('.variant-selector option').attr('disabled', false);
    $('.variant-selector:not([data-type="' + variant_type + '"]) option').each(function() {
      const other_val = this.valueif (!$('option').is('[data-' + variant_type + '="' + val + '"][data-' + other_type + '="' + other_val + '"]')) {
        this.disabled = true;
      }
    });
    var option = $(this).parent('form').find('.variant-selector').children(":selected").get().map(function(el) {
      return el.value
    }).join(" / ");

    var stringOption = "'" + option + "'";
    $('select[name="id"] option[value=' + stringOption + ']').prop('selected', true);

  });
});
<scriptsrc="https://code.jquery.com/jquery-3.6.0.min.js"></script><formaction="#"method="post"><selectclass="variant-selector"data-type="Size"><optionvalue="S">S</option><optionvalue="M">M</option><optionvalue="L">L</option><optionvalue="XL">XL</option></select><selectclass="variant-selector"data-type="Color"><optionvalue="Grey">Grey</option><optionvalue="Red">Red</option><optionvalue="White">White</option></select><br><selectname="id"><optiondata-size="M"data-color="Grey"value="M / Grey">M / Grey</option><optiondata-size="L"data-color="Grey"value="L / Grey">L / Grey</option><optiondata-size="S"data-color="Red"value="S / Red">S / Red</option><optiondata-size="L"data-color="Red"value="L / Red">L / Red</option><optiondata-size="M"data-color="White"value="M / White">M / White</option><optiondata-size="L"data-color="White"value="L / White">L / White</option><optiondata-size="XL"data-color="Red"value="XL / Red">XL / Red</option></select></form>

Post a Comment for "How To Hide And Auto Select Option Using Data-attributes?"