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.value
if (!$('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);
});
});
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<form action="#" method="post">
<select class="variant-selector" data-type="Size">
<option value="S">S</option>
<option value="M">M</option>
<option value="L">L</option>
<option value="XL">XL</option>
</select>
<select class="variant-selector" data-type="Color">
<option value="Grey">Grey</option>
<option value="Red">Red</option>
<option value="White">White</option>
</select>
<br>
<select name="id">
<option data-size="M" data-color="Grey" value="M / Grey">M / Grey</option>
<option data-size="L" data-color="Grey" value="L / Grey">L / Grey</option>
<option data-size="S" data-color="Red" value="S / Red">S / Red</option>
<option data-size="L" data-color="Red" value="L / Red">L / Red</option>
<option data-size="M" data-color="White" value="M / White">M / White</option>
<option data-size="L" data-color="White" value="L / White">L / White</option>
<option data-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?"