帝国模板之家为广大用户提供专业、一站式建站服务。

网页特效

网页特效栏目收集了最全最新的前端网页插件,包括最流行的jQuery,Bootstrap,Js,Css,Vue等主流特效插件。

当前位置:首页 > 资源 > 网页特效 > 正文

jquery(MagicSuggest)响应式下拉多选框插件

帝国模板之家 2020-11-05 网页特效 评论

MagicSuggest是一款简单易于使用jQuery插件,输入的文字可以响应式匹配到下拉列表中的选项,可多选。

功能:

  1. 响应设计。

  2. 兼容bootstrap3和bootstrap4框架。

  3. 通过AJAX动态加载数据。

  4. 自定义查询参数。

  5. 数据排序和过滤。

1.加载jQuery MagicSuggest插件和bootstrap的样式文件

<link rel="stylesheet" href="/path/to/cdn/bootstrap.min.css" />
<link href="magicsuggest.css" rel="stylesheet" />

2. 创建一个空的容器,用于生成组合列表。

<div id="example" class="form-control"></div>

3. 加载jQuery MagicSuggest插件和jquery js文件。

<script src="jquery.min.js"></script>
<script src="magicsuggest.js"></script>

4. 准备好JSON数据用于填充组合框。有3选项可用:

  1. 空: 组合框不会显示任何东西。

  2. 静态数据:你可以通过一个JSON对象数组,字符串数组,甚至是一个CSV字符串作为数据源。数据格式:(* {id: 0,名字:“巴黎”},{id: 1、名称:“纽约”}]。

  3. URL:可以通过组件的url获取JSON数据。

  4. function:你可以传递一个函数返回一个JSON对象数组(例:[{id:…,名字:…},{…}))。 函数可以返回的JSON数据,也可以使用第一个参数是函数来处理数据。 只有一个(回调函数或返回值)是成功所需的功能。

5. 初始化数据

var myData = ['New York','Los Angeles','Chicago', ...]
$(function() {
  var instance = $('#example').magicSuggest({
    data: myData
  });
});

6. 自定义模板render函数

$(function() {
  var instance = $('#example').magicSuggest({
    data: myData,
    renderer: function(data){
      return '<div style="padding: 5px; overflow:hidden;">' +
          '<div style="float: left;"><img src="' + data.picture + '" /></div>' +
          '<div style="float: left; margin-left: 5px">' +
              '<div style="font-weight: bold; color: #333; font-size: 10px; line-height: 11px">' + data.name + '</div>' +
              '<div style="color: #999; font-size: 9px">' + data.email + '</div>' +
          '</div>' +
      '</div><div style="clear:both;"></div>'; // make sure we have closed our dom stuff
    }
  });
});

7. 默认配置选项和回调方法

/**********  CONFIGURATION PROPERTIES ************/
/**
 * Restricts or allows the user to validate typed entries.
 * Defaults to true.
 */
allowFreeEntries: true,

/**
 * Restricts or allows the user to add the same entry more than once
 * Defaults to false.
 */
allowDuplicates: false,

/**
 * Additional config object passed to each $.ajax call
 */
ajaxConfig: {},

/**
 * If a single suggestion comes out, it is preselected.
 */
autoSelect: true,

/**
 * Auto select the first matching item with multiple items shown
 */
selectFirst: false,

/**
 * Allow customization of query parameter
 */
queryParam: 'query',

/**
 * A function triggered just before the ajax request is sent, similar to jQuery
 */
beforeSend: function(){ },

/**
 * A custom CSS class to apply to the field's underlying element.
 */
cls: '',

/**
 * JSON Data source used to populate the combo box. 3 options are available here:
 * No Data Source (default)
 *    When left null, the combo box will not suggest anything. It can still enable the user to enter
 *    multiple entries if allowFreeEntries is * set to true (default).
 * Static Source
 *    You can pass an array of JSON objects, an array of strings or even a single CSV string as the
 *    data source.For ex. data: [* {id:0,name:"Paris"}, {id: 1, name: "New York"}]
 *    You can also pass any json object with the results property containing the json array.
 * Url
 *     You can pass the url from which the component will fetch its JSON data.Data will be fetched
 *     using a POST ajax request that will * include the entered text as 'query' parameter. The results
 *     fetched from the server can be:
 *     - an array of JSON objects (ex: [{id:...,name:...},{...}])
 *     - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
 *     - a JSON object whose data will be contained in the results property
 *      (ex: {results: [{id:...,name:...},{...}]
 * Function
 *     You can pass a function which returns an array of JSON objects  (ex: [{id:...,name:...},{...}])
 *     The function can return the JSON data or it can use the first argument as function to handle the data.
 *     Only one (callback function or return value) is needed for the function to succeed.
 *     See the following example:
 *     function (response) { var myjson = [{name: 'test', id: 1}]; response(myjson); return myjson; }
 */
data: null,

/**
 * Additional parameters to the ajax call
 */
dataUrlParams: {},

/**
 * Start the component in a disabled state.
 */
disabled: false,

/**
 * Name of JSON object property that defines the disabled behaviour
 */
disabledField: null,

/**
 * Name of JSON object property displayed in the combo list
 */
displayField: 'name',

/**
 * Set to false if you only want mouse interaction. In that case the combo will
 * automatically expand on focus.
 */
editable: true,

/**
 * Set starting state for combo.
 */
expanded: false,

/**
 * Automatically expands combo on focus.
 */
expandOnFocus: false,

/**
 * JSON property by which the list should be grouped
 */
groupBy: null,

/**
 * Set to true to hide the trigger on the right
 */
hideTrigger: false,

/**
 * Set to true to highlight search input within displayed suggestions
 */
highlight: true,

/**
 * A custom ID for this component
 */
id: null,

/**
 * A class that is added to the info message appearing on the top-right part of the component
 */
infoMsgCls: '',

/**
 * Additional parameters passed out to the INPUT tag. Enables usage of AngularJS's custom tags for ex.
 */
inputCfg: {},

/**
 * The class that is applied to show that the field is invalid
 */
invalidCls: 'ms-inv',

/**
 * Set to true to filter data results according to case. Useless if the data is fetched remotely
 */
matchCase: false,

/**
 * Once expanded, the combo's height will take as much room as the # of available results.
 *    In case there are too many results displayed, this will fix the drop down height.
 */
maxDropHeight: 290,

/**
 * Defines how long the user free entry can be. Set to null for no limit.
 */
maxEntryLength: null,

/**
 * A function that defines the helper text when the max entry length has been surpassed.
 */
maxEntryRenderer: function(v) {
    return 'Please reduce your entry by ' + v + ' character' + (v > 1 ? 's':'');
},

/**
 * The maximum number of results displayed in the combo drop down at once.
 */
maxSuggestions: null,

/**
 * The maximum number of items the user can select if multiple selection is allowed.
 *    Set to null to remove the limit.
 */
maxSelection: 10,

/**
 * A function that defines the helper text when the max selection amount has been reached. The function has a single
 *    parameter which is the number of selected elements.
 */
maxSelectionRenderer: function(v) {
    return 'You cannot choose more than ' + v + ' item' + (v > 1 ? 's':'');
},

/**
 * The method used by the ajax request.
 */
method: 'POST',

/**
 * The minimum number of characters the user must type before the combo expands and offers suggestions.
 */
minChars: 0,

/**
 * A function that defines the helper text when not enough letters are set. The function has a single
 *    parameter which is the difference between the required amount of letters and the current one.
 */
minCharsRenderer: function(v) {
    return 'Please type ' + v + ' more character' + (v > 1 ? 's':'');
},

/**
 * Whether or not sorting / filtering should be done remotely or locally.
 * Use either 'local' or 'remote'
 */
mode: 'local',

/**
 * The name used as a form element.
 */
name: null,

/**
 * The text displayed when there are no suggestions.
 */
noSuggestionText: 'No suggestions',

/**
 * The default placeholder text when nothing has been entered
 */
placeholder: 'Type or click here',

/**
 * A function used to define how the items will be presented in the combo
 */
renderer: null,

/**
 * Whether or not this field should be required
 */
required: false,

/**
 * Set to true to render selection as a delimited string
 */
resultAsString: false,

/**
 * Text delimiter to use in a delimited string.
 */
resultAsStringDelimiter: ',',

/**
 * Name of JSON object property that represents the list of suggested objects
 */
resultsField: 'results',

/**
 * A custom CSS class to add to a selected item
 */
selectionCls: '',

/**
 * An optional element replacement in which the selection is rendered
 */
selectionContainer: null,

/**
 * Where the selected items will be displayed. Only 'right', 'bottom' and 'inner' are valid values
 */
selectionPosition: 'inner',

/**
 * A function used to define how the items will be presented in the tag list
 */
selectionRenderer: null,

/**
 * Set to true to stack the selectioned items when positioned on the bottom
 *    Requires the selectionPosition to be set to 'bottom'
 */
selectionStacked: false,

/**
 * Direction used for sorting. Only 'asc' and 'desc' are valid values
 */
sortDir: 'asc',

/**
 * name of JSON object property for local result sorting.
 *    Leave null if you do not wish the results to be ordered or if they are already ordered remotely.
 */
sortOrder: null,

/**
 * If set to true, suggestions will have to start by user input (and not simply contain it as a substring)
 */
strictSuggest: false,

/**
 * Custom style added to the component container.
 */
style: '',

/**
 * If set to true, the combo will expand / collapse when clicked upon
 */
toggleOnClick: false,


/**
 * Amount (in ms) between keyboard registers.
 */
typeDelay: 400,

/**
 * If set to true, tab won't blur the component but will be registered as the ENTER key
 */
useTabKey: false,

/**
 * If set to true, using comma will validate the user's choice
 */
useCommaKey: true,


/**
 * Determines whether or not the results will be displayed with a zebra table style
 */
useZebraStyle: false,

/**
 * initial value for the field
 */
value: null,

/**
 * name of JSON object property that represents its underlying value
 */
valueField: 'id',

/**
 * regular expression to validate the values against
 */
vregex: null,

/**
 * type to validate against
 */
vtype: null

8. 方法

var instance = $('#example').magicSuggest({
    // options here
  });


// adds items to the selection
instance.addToSelection([object] objs, [boolean] silent) 

// clears the selection
instance.clear([boolean] silent)

// collapses the combo list
instance.collapse([boolean] silent)

// disables the combo list
instance.disable()

// removes what the user was typing
instance.empty()

// enables the compolist
instance.enable()

// expands the component
instance.expand()

// returns the combo suggestions
instance.getData() 

// returns the status of the component
instance.isDisabled() 

// checks if the selection is valid
instance.isValid() 

// returns the list of extra URL paramaters set for AJAX requests
instance.getDataUrlParams() 

// returns the name used for HTML form submission
instance.getName() 

// returns an array of selected JSON objects
instance.getSelection() 

// returns the current text being entered by the user
instance.getRawValue() 

// returns an array containing only the selected JSON values
instance.getValue() 

// removes items from the selection
instance.removeFromSelection([object] objs, [boolean] silent) 

// sets the objects listed in the combo
instance.setData([array] cbItems) 

// sets the name to be used for form submission
instance.setName([string] name) 

// sets the selection with a given array of objects
instance.setSelection(object[]) 

// sets the selection according to given values
instance.setValue([array] ids) 

// sets extra parameters for AJAX requests
instance.setDataUrlParams([object] params) 

9. 事件

var instance = $('#example').magicSuggest({
    // options here
  });

instance.on( "beforeload", function(e, this) {
  // fired before the AJAX request is performed
});

instance.on( "blur", function(e, this) {
  // fired when the component looses focus
});

instance.on( "collapse", function(e, this) {
  // fired when the combo is collapsed
});

instance.on( "expand", function(e, this) {
  // fired when the combo is expanded
});

instance.on( "focus", function(e, this) {
  // fired when the combo gains focus
});

instance.on( "keydown", function(e, this, keyevent) {
  // fired when the user presses a key
});

instance.on( "keyup", function(e, this, keyevent) {
  // fired when the user releases a key
});

instance.on( "load", function(e, this, records[]) {
  // fired when the AJAX request has been performed
});

instance.on( "selectionchange", function(e, this, records[]) {
  // fired when the user has changed the selection
});

instance.on( "triggerclick", function(e, this) {
  // fired when the user has changed the selection
});

会员登陆后即可下载资源文件。更多好用网站特效插件,请关注帝国模板之家

这世上无忧无虑的人,反而相对寿命会长点。

已有 位小伙伴发表了看法

欢迎 发表评论

  • 匿名发表

关于

帝国cms模板

网页插件

帝国模板之家 | www.moyouyouw.cn

本站所有模板/文章除标明原创外,均来自网络转载,版权归原作者所有,如果有侵犯到您的权益,请联系站长删除,谢谢! 寻找帝国cms模板首选帝国模板之家,用心做站,上线至今广受好评,值得信赖!

  • 交流群1:帝国cms交流群1
  • 交流群2:帝国cms交流群2
在线QQ 给我留言