I have a dropdown menu with options, and I want to alter these with jQuery based on their data-* attribute (in this case, hide all options, then show only the ones with X attribute)
Dropdown:
<button onclick="changeopts(10)">click me</button>
<select id="testsel">
<option data-test="10" value="0">opt1</option>
<option data-test="11" value="5">opt2</option>
<option data-test="12" value="200">opt3</option>
</select>
Javascript:
function changeopts(show){
var opts = document.getElementById("testsel").options;
$(opts).prop('disabled',true);
$(opts).css('display','none');
if ($(opts).attr('data-test')==show){
$(opts).prop('disabled',false);
$(opts).css('display','inline');
}
}
This doesn't work. I assume the if statement can't look at all of the options at the same time. I want to avoid looping through all the options if possible.
Solution that I used:
function changeopts(show){
var opts = document.getElementById("testsel").options;
$(opts).prop('disabled',true);
$(opts).css('display','none');
$('#testsel option[data-test="'+show+'"]').prop('disabled',false);
$('#testsel option[data-test="'+show+'"]').css('display','inline');
}