Optgroup будет выглядеть следующим образом.Это соответствует вашим потребностям?
// '<value>': '<text>'
var group_members = {
'1': {
'11': '11',
'12': '12',
},
'2': {
'21': '21',
'22': '22',
},
'3': {
'31': '31',
'32': '32',
},
};
$('select[name=group]').on('change', function() {
var $selectMember = $('select[name=group_member]');
// clear options
$selectMember.find('optgroup').remove();
$selectMember.find('option').remove();
// source here is 'group_members'
// if you have much data i recommend using ajax here to query data by a script
// as JSON have a look at AJAX - jQuery.ajax
var selectedGroups = $(this).val();
for(var i in selectedGroups) {
var selectedGroup = selectedGroups[i];
var optgroup = $('<optgroup>').attr('label', selectedGroup);
for(var value in group_members[selectedGroup]) {
optgroup
.append(
($('<option>', { value: value })
.text(group_members[selectedGroup][value]))
);
}
$selectMember.append(optgroup);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Hold ctrl to select multiple
<hr />
Group:
<select name="group" multiple size=5>
<option value=''>Please Select</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
Group Members:
<select name='group_member' size=5 multiple></select>