Hi Corobori,
var Group = jQuery('<optgroup/>', {
label: $(this)[0]
}).appendTo(selectControl);
var grpItems = $(selectControl).find('option[data-group="' + $(this)[0] + '"]');
You need to replace the above line of code.
Please refer below sample.
HTML
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
GroupDropdownlist('ddlCategories')
});
function GroupDropdownlist(id) {
var selectControl = $('#' + id);
var groups = [];
$(selectControl).find('option').each(function () {
groups.push($(this).attr('data-group'));
});
var uniqueGroup = groups.filter(function (itm, i, a) {
return i == a.indexOf(itm);
});
$(uniqueGroup).each(function () {
var Group = jQuery('<optgroup/>', {
label: this
}).appendTo(selectControl);
var grpItems = $(selectControl).find('option[data-group="' + this + '"]');
$(grpItems).each(function () {
var item = $(this);
item.appendTo(Group);
});
});
}
</script>
</head>
<body>
<div>
<select name="ddlCategories" id="ddlCategories">
<option value="1" data-group="Science">BSC-IT</option>
<option value="2" data-group="Science">BSC-CS</option>
<option value="3" data-group="Science">BSC</option>
<option value="4" data-group="Commerce">BCOM-Marketing</option>
<option value="5" data-group="Commerce">BCOM-Finance</option>
<option value="6" data-group="Arts">BA</option>
<option value="6" data-group="Arts">MA</option>
</select>
</div>
</body>
</html>
Demo