How can I add option groups in ASP.NET drop down list?

后端 未结 10 1167
遇见更好的自我
遇见更好的自我 2020-11-28 10:22

I have a requirement of grouping the drop down list options in ASP.NET drop down server control. Do you have any idea to how to approach the issue? I am new to ASP.NET.

10条回答
  •  粉色の甜心
    2020-11-28 11:06

    Here's what I did, with jquery-only, no server side changes:

    /* Add Option Groups to Note Dropdown */
    var $select = $('#<%= DropDownListIDHere.ClientID %>');
    var optGroup;
    $('#<%= DropDownListIDHere.ClientID %> option').each(function () {
        if ($(this).val() == '<') {
            /* Opener */
            optGroup = $('').attr('label', $(this).text());
        } else if ($(this).val() == '>') {
            /* Closer */
            $('').appendTo(optGroup);
            optGroup.appendTo($select);
            optGroup = null;
        } else {
            /* Normal Item */
            if (optGroup) {
                $('').attr('value', $(this).val()).appendTo(optGroup);
            } else {
                $('').attr('value', $(this).val()).appendTo($select);
            }
        }
        $(this).remove();
    });
    

    Then, you just add specific items as openers and closers with value < and > like so:

    
    
    
    
    
    

    Super simple, no new controls needed, only targets the select you want to change, and doesn't require every item to be in an optgroup.

提交回复
热议问题