Issue with select2 and option group
09:54 21 Nov 2025

I am adding a new option to a select2 optiongroup with custom drawing of options. here is my code:

 
function defaultParameter(value, defaultValue) {
    return typeof value !== 'undefined' ? value : defaultValue;
}
    /**
     * @param {jQuery} $dropDown
     * @param {string} value
     * @param {string} caption
     * @param {string} [icon] Sets the value of eh-icon to be rendered by the Select2. If this is not set or set to '' then this is ignored.
     * @param {boolean} [selectItem] Defaults to true
     * @param {string} [optionGroup] The option group that this option belongs to.
     */
    function addOptionToSelect2($dropDown, value, caption, icon, selectItem, optionGroup) {
        value = value.replaceAll('-', '');
        let $option = $dropDown.find(`option[value=${value}]`);
        if ($option.length) {
            $option.text(caption);
            if (selectItem) {
                $dropDown.val(value).trigger(EventBindings.Change);
            }
            return;
        }
        
        selectItem = defaultParameter(selectItem, true);
        
        let newOption = createElement('option');
        newOption.attr(Attributes.Value, value);
        newOption.text(caption);
        
        
        optionGroup = defaultParameter(optionGroup, '');

        if (optionGroup === '') {
            $dropDown.append(newOption).trigger(EventBindings.Change);
        }
        else {
            $dropDown.find(`optgroup[label="${optionGroup}"]`).append(newOption);
        }
        
        if (selectItem) {
            $dropDown.val(value).trigger(EventBindings.Change);
        }
   }

But the value has been added to the applicable option group.

HTML (The drop down is contained in a bootstrap modal):


As far as I can tell I am following the instructions here:

Add dynamic option inside optgroup to a select2

javascript jquery jquery-select2