jquerycssjquery-uijquery-ui-selectmenu

jquery-ui: how to set the class name in the selectmenu item (option)?


I have a <select> form in which a unique class is set for one option:

<select id='mylist'>
    <option value = '1'>One</option>
    <option value = '2' class='my_element'>Two</option>
</select>

When I connect selectmenu

$('#mylist').selectmenu();

Class in new selectmenu object disappears (does not appear)

<li class="ui-menu-item"><div id="ui-id-3" tabindex="-1" role="option" class="ui-menu-item-wrapper">Two</div></li>

How to fix it? I want

<li class="ui-menu-item"><div id="ui-id-3" tabindex="-1" role="option" class="ui-menu-item-wrapper my_element">Two</div></li>

OR

<li class="ui-menu-item my_element"><div id="ui-id-3" tabindex="-1" role="option" class="ui-menu-item-wrapper">Two</div></li>

Solution

  • You can overwrite _renderMenu():

    $('#mylist').selectmenu().data("ui-selectmenu")._renderMenu = function(ul, items) {
        var that = this;
        items.forEach(function(ele, idx) {
            var li = that._renderItemData(ul, ele);
            if (ele.element.get(0).classList.length>0) {
                // preserve original classes...
                li.addClass(ele.element.get(0).classList.value);
            }
        });
    };
    .my_element {
        background-color: red;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link href="https://code.jquery.com/ui/1.12.0/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
    <script src="https://code.jquery.com/ui/1.12.0/jquery-ui.js"></script>
    
    <select id='mylist'>
        <option value='1'>One</option>
        <option value='2' class='my_element'>Two</option>
    </select>