— Append parent_ to all your top level options’ values like: parent_Course A, parent_Course B
— Also add extra options with the value as “endparent” something like below structure
parent_Course A:
course 1
course 2
course 3
course 4
endparent
parent_Course B:
course 1
course 2
course 3
endparent
Code:
// contact us form - change out optgroup labels
$(function() {
// search for parent_ items
var foundin = $('option:contains("parent_")');
$.each(foundin, function(value) {
var updated = $(this).val().replace("parent_","");
// find all following elements until endparent
$(this).nextUntil('option:contains("endparent")')
.wrapAll('<optgroup label="'+ updated +'"></optgroup');
});
// remove placeholder options
$('option:contains("parent_")').remove();
$('option:contains("endparent")').remove();
});