New to Kendo UI for jQuery? Download free 30-day trial

Sort Displayed Columns Menu Items

Environment

Product Progress® Kendo UI® Grid for jQuery
Created with version 2019.1.115

Description

My Grid has a column menu, which contains displayed columns submenu.

How can I sort the items of the displayed columns submenu?

  • As of Kendo UI R3 2020 SP1(v2020.3.1021) the columns submenu can be sorted via the columnMenu.columns.sort configuration.

Solution

A possible solution is to sort the li elements of the column menu within the columnMenuInit event of the widget.

    <div id="example">
      <div id="grid"></div>

      <script>
        $(document).ready(function() {
          $("#grid").kendoGrid({
            dataSource: {
              type: "odata",
              transport: {
                read: "https://demos.telerik.com/kendo-ui/service/Northwind.svc/Orders"
              },
              schema: {
                model: {
                  fields: {
                    OrderID: { type: "number" },
                    ShipCountry: { type: "string" },
                    ShipName: { type: "string" },
                    ShipAddress: { type: "string" }                                        
                  }
                }
              },
              pageSize: 30,
              serverPaging: true,
              serverFiltering: true,
              serverSorting: true
            },
            height: 550,
            sortable: true,
            filterable: true,
            columnMenu: true,
            pageable: true,
            columns: [ {
              field: "OrderID",
              title: "Order ID",
              width: 120
            }, {
              field: "ShipCountry",
              title: "Ship Country"
            }, {
              field: "ShipName",
              title: "Ship Name"
            },  {
              field: "ShipAddress",
              filterable: false
            }],
            columnMenuInit:function(e){
              var list= e.container.find('.k-columns-item ul')
              var items = list.find('li');

              items.each(function(x,y){
                $(y).removeClass('k-first k-last')
              }) 

              items.sort(function(a,b){
                a = $(a);
                b = $(b);

                var firstText = a.find('input[data-field]').attr('data-field');
                var secondText = b.find('input[data-field]').attr('data-field');

                return ((firstText < secondText) ? -1 : ((firstText > secondText) ? 1 : 0));
              })

              items.first().addClass('k-first');
              items.last().addClass('k-last');

              items.each(function(y,x){
                list.append($(x));
              })
            }
          });
        });
      </script>
    </div>
In this article