JSFiddle - React, Tailwind, and code Playground
by cbruen1
HTML
<select id="select_A" multiple="multiple" size="10">
<optgroup label="group 1">
<option value="1cowrat" id="main1">1 - cow/rat</option>
<option value="2 - cat, dog and lion" id="main2">2 - cat, dog and lion</option>
<optgroup label="group 2">
<option value="3-," id="main3">3 - mantis</option>
</select>
<select id="select_B" multiple="multiple" size="10">
<optgroup label="1cowrat" id="sub1" style="display:none;">
<option value="1A">1A</option>
<option value="1B">1B</option>
<optgroup label="2 - cat, dog and lion" id="sub2" style="display:none;">
<option value="2A">2A</option>
<option value="2B">2B</option>
<optgroup label="3-," id="sub3" style="display:none;">
<option value="3A">3A</option>
<option value="3B">3B</option>
</select>
JavaScript
$(document).ready(function () {
$.fn.hideOptionGroup = function () {
$(this).hide();
$(this).children().each(function () {
$(this).attr("disabled", "disabled").removeAttr("selected");
});
$(this).appendTo($(this).parent());
}
$.fn.showOptionGroup = function () {
$(this).show();
$(this).children().each(function () {
$(this).removeAttr("disabled");
});
$(this).prependTo($(this).parent());
$(this).parent().animate({
scrollTop: 0
}, 0);
};
$("#sub1,#sub2,#sub3").showOptionGroup();
// $("#sub1,#sub2").hideOptionGroup();
$("#select_A").change(function () {
$("#select_B").children("optgroup").children().prop("disabled", "disabled").prop("selected", false);
var arr = $(this).val();
for (var i = 0; i < arr.length; i++) {
$("#select_B").children("optgroup[label='" + arr[i] + "']").children().prop("disabled", false).prop("selected", "selected");
}
$("#select_B").focus();
});
});