Wednesday, May 25, 2016

jQuery UI Multicolumn Autocomplete Widget Plugin 2.1

custom.mcautocomplete.js:

/*
 * jQuery UI Multicolumn Autocomplete Widget Plugin 2.1
 * Copyright (c) 2012-2014 Mark Harmon
 *
 * Depends:
 * - jQuery UI Autocomplete widget
 *
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 */
$.widget('custom.mcautocomplete', $.ui.autocomplete, {
  _create: function () {
    this._super();
    this.widget().menu("option", "items", "> :not(.ui-widget-header)");
  },
  _renderMenu: function (ul, items) {
    var that = this;

    if (this.options.showHeader) {
      row = $('<div class="row ui-widget-header" style="position: fixed; z-index: 18003; width: 600px; margin: 0px;">');

      $.each(this.options.columns, function (index, column) {
        row.append('<div class="' + column.colClass + '">' + column.text + '</div>');
      });

      ul.append(row);
    }

    $.each(items, function (index, item) {
      that._renderItemData(ul, item);
    });
  },
  _renderItem: function (ul, item) {
    row = $('<div class="row">');

    if (this.options.showHeader) {
      $.each(this.options.columns, function (index, column) {
        row.append('<div class="' + column.colClass + '">' + item[column.field] + '</div>');
      });
    }

    return $('<li>')
      .attr('data-value', item.value)
      //.data('ui-autocomplete-item', item)
      .append(row)
      .appendTo(ul);
  }
});

Example:

    $('#ItemNum').mcautocomplete({
      showHeader: true,
      columns: [
        {field: 'ItemNum', text: 'ItemNum', colClass: 'col-lg-6'},
        {field: 'ItemName', text: 'ItemName', colClass: 'col-lg-6'},
      ],
      minLength: 1,
      autoFocus: true,
      source: function (request, response) {
        var optObj = {};
        optObj.ItemNum = request.term;

        $.ajax({url: '/index?act=ListItemInventory', data: JSON.stringify(optObj),
          success: function(dataObj) {
            if (dataObj.Status == true) {
              response(dataObj.ItemInventoryArr);
            } else {
              response([]);
            }
          },
          error: function(dataObj) {
            response([]);
          },
        });
      },
      create: function(event, ui) {
        $(this).mcautocomplete("widget").css({
          height: 200,
          "overflow-x": "hidden",
          "overflow-y": "scroll",
        });
        $(this).data('custom-mcautocomplete')._resizeMenu = function() {
          this.menu.element.outerWidth(600);
        };
      },
      select: function(event, ui) {
        $(this).val(ui.item.Item.ItemNum);
      },
      close: function(event, ui) {
      },
    });

Reference:

http://jsfiddle.net/alforno/g4stl/

No comments: