jQuery 简单响应多选插件 MagicSuggest

  • 源码大小:24.97KB
  • 所需积分:1积分
  • 源码编号:19JP-3637
  • 浏览次数:825次
  • 最后更新:2023年07月05日
  • 所属栏目:表单
本站默认解压密码:19jp.com 或 19jp_com

简介

MagicSuggest是一个易于使用的jQuery插件,用于创建一个组合列表,使您能够从下拉列表中选择多个项目(例如标签、令牌、电子邮件地址等),并支持打字和自动完成。

更多功能:

  • 响应式设计。
  • 与Bootstrap 3和Bootstrap 4框架兼容。
  • 通过AJAX动态加载数据。
  • 自定义查询参数。
  • 数据排序和过滤。
  • 复杂的模板。
  • 大量配置选项。

基本用法:

1.在网页的头部加载jQueryMagicSugest插件的CSS和Bootstrap的样式表。

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

2.创建一个空容器,您想在其中生成组合列表。

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

3.在文档末尾加载jQuery JavaScript库和jQuery MagicSuguest插件的JavaScript。

  1. <script src="/path/to/cdn/jquery.min.js"></script>
  2. <script src="magicsuggest.js"></script>

4.准备用于填充组合框的JSON数据。这里有3个选项:

  • 无数据源(默认):如果留空,组合框将不会显示任何内容。如果allowFreeEntries被*设置为true(默认值),它仍然可以让用户输入多个条目。
  • 静态来源:您可以传递一个JSON对象数组、一个字符串数组,甚至一个CSV字符串作为数据源。例如数据:[*{id:0,name:“Paris”},{id:1,name:”New York“}]。您还可以传递任何带有results属性的json对象,该属性包含json数组。
  • 网址:您可以传递url,组件将从中获取JSON数据。数据将使用POST ajax请求获取,该请求将*包括输入的文本作为“query”参数
  • 功能:您可以传递一个返回JSON对象数组的函数(例如:〔{id:…,name:…},{…}〕)。该函数可以返回JSON数据,也可以使用第一个参数作为函数来处理数据。函数成功只需要一个(回调函数或返回值)。
  1. var myData = ['New York','Los Angeles','Chicago', ...]

5.初始化jQuery MagicSuggest插件,并用您自己的数据填充组合列表。

  1. $(function() {
  2. var instance = $('#example').magicSuggest({
  3. data: myData
  4. });
  5. });

6.使用自定义模板提供作用

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

7.所有默认配置选项、功能和回调。

  1. /********** CONFIGURATION PROPERTIES ************/
  2. /**
  3. * Restricts or allows the user to validate typed entries.
  4. * Defaults to true.
  5. */
  6. allowFreeEntries: true,
  7.  
  8. /**
  9. * Restricts or allows the user to add the same entry more than once
  10. * Defaults to false.
  11. */
  12. allowDuplicates: false,
  13.  
  14. /**
  15. * Additional config object passed to each $.ajax call
  16. */
  17. ajaxConfig: {},
  18.  
  19. /**
  20. * If a single suggestion comes out, it is preselected.
  21. */
  22. autoSelect: true,
  23.  
  24. /**
  25. * Auto select the first matching item with multiple items shown
  26. */
  27. selectFirst: false,
  28.  
  29. /**
  30. * Allow customization of query parameter
  31. */
  32. queryParam: 'query',
  33.  
  34. /**
  35. * A function triggered just before the ajax request is sent, similar to jQuery
  36. */
  37. beforeSend: function(){ },
  38.  
  39. /**
  40. * A custom CSS class to apply to the field's underlying element.
  41. */
  42. cls: '',
  43.  
  44. /**
  45. * JSON Data source used to populate the combo box. 3 options are available here:
  46. * No Data Source (default)
  47. * When left null, the combo box will not suggest anything. It can still enable the user to enter
  48. * multiple entries if allowFreeEntries is * set to true (default).
  49. * Static Source
  50. * You can pass an array of JSON objects, an array of strings or even a single CSV string as the
  51. * data source.For ex. data: [* {id:0,name:"Paris"}, {id: 1, name: "New York"}]
  52. * You can also pass any json object with the results property containing the json array.
  53. * Url
  54. * You can pass the url from which the component will fetch its JSON data.Data will be fetched
  55. * using a POST ajax request that will * include the entered text as 'query' parameter. The results
  56. * fetched from the server can be:
  57. * - an array of JSON objects (ex: [{id:...,name:...},{...}])
  58. * - a string containing an array of JSON objects ready to be parsed (ex: "[{id:...,name:...},{...}]")
  59. * - a JSON object whose data will be contained in the results property
  60. * (ex: {results: [{id:...,name:...},{...}]
  61. * Function
  62. * You can pass a function which returns an array of JSON objects (ex: [{id:...,name:...},{...}])
  63. * The function can return the JSON data or it can use the first argument as function to handle the data.
  64. * Only one (callback function or return value) is needed for the function to succeed.
  65. * See the following example:
  66. * function (response) { var myjson = [{name: 'test', id: 1}]; response(myjson); return myjson; }
  67. */
  68. data: null,
  69.  
  70. /**
  71. * Additional parameters to the ajax call
  72. */
  73. dataUrlParams: {},
  74.  
  75. /**
  76. * Start the component in a disabled state.
  77. */
  78. disabled: false,
  79.  
  80. /**
  81. * Name of JSON object property that defines the disabled behaviour
  82. */
  83. disabledField: null,
  84.  
  85. /**
  86. * Name of JSON object property displayed in the combo list
  87. */
  88. displayField: 'name',
  89.  
  90. /**
  91. * Set to false if you only want mouse interaction. In that case the combo will
  92. * automatically expand on focus.
  93. */
  94. editable: true,
  95.  
  96. /**
  97. * Set starting state for combo.
  98. */
  99. expanded: false,
  100.  
  101. /**
  102. * Automatically expands combo on focus.
  103. */
  104. expandOnFocus: false,
  105.  
  106. /**
  107. * JSON property by which the list should be grouped
  108. */
  109. groupBy: null,
  110.  
  111. /**
  112. * Set to true to hide the trigger on the right
  113. */
  114. hideTrigger: false,
  115.  
  116. /**
  117. * Set to true to highlight search input within displayed suggestions
  118. */
  119. highlight: true,
  120.  
  121. /**
  122. * A custom ID for this component
  123. */
  124. id: null,
  125.  
  126. /**
  127. * A class that is added to the info message appearing on the top-right part of the component
  128. */
  129. infoMsgCls: '',
  130.  
  131. /**
  132. * Additional parameters passed out to the INPUT tag. Enables usage of AngularJS's custom tags for ex.
  133. */
  134. inputCfg: {},
  135.  
  136. /**
  137. * The class that is applied to show that the field is invalid
  138. */
  139. invalidCls: 'ms-inv',
  140.  
  141. /**
  142. * Set to true to filter data results according to case. Useless if the data is fetched remotely
  143. */
  144. matchCase: false,
  145.  
  146. /**
  147. * Once expanded, the combo's height will take as much room as the # of available results.
  148. * In case there are too many results displayed, this will fix the drop down height.
  149. */
  150. maxDropHeight: 290,
  151.  
  152. /**
  153. * Defines how long the user free entry can be. Set to null for no limit.
  154. */
  155. maxEntryLength: null,
  156.  
  157. /**
  158. * A function that defines the helper text when the max entry length has been surpassed.
  159. */
  160. maxEntryRenderer: function(v) {
  161. return 'Please reduce your entry by ' + v + ' character' + (v > 1 ? 's':'');
  162. },
  163.  
  164. /**
  165. * The maximum number of results displayed in the combo drop down at once.
  166. */
  167. maxSuggestions: null,
  168.  
  169. /**
  170. * The maximum number of items the user can select if multiple selection is allowed.
  171. * Set to null to remove the limit.
  172. */
  173. maxSelection: 10,
  174.  
  175. /**
  176. * A function that defines the helper text when the max selection amount has been reached. The function has a single
  177. * parameter which is the number of selected elements.
  178. */
  179. maxSelectionRenderer: function(v) {
  180. return 'You cannot choose more than ' + v + ' item' + (v > 1 ? 's':'');
  181. },
  182.  
  183. /**
  184. * The method used by the ajax request.
  185. */
  186. method: 'POST',
  187.  
  188. /**
  189. * The minimum number of characters the user must type before the combo expands and offers suggestions.
  190. */
  191. minChars: 0,
  192.  
  193. /**
  194. * A function that defines the helper text when not enough letters are set. The function has a single
  195. * parameter which is the difference between the required amount of letters and the current one.
  196. */
  197. minCharsRenderer: function(v) {
  198. return 'Please type ' + v + ' more character' + (v > 1 ? 's':'');
  199. },
  200.  
  201. /**
  202. * Whether or not sorting / filtering should be done remotely or locally.
  203. * Use either 'local' or 'remote'
  204. */
  205. mode: 'local',
  206.  
  207. /**
  208. * The name used as a form element.
  209. */
  210. name: null,
  211.  
  212. /**
  213. * The text displayed when there are no suggestions.
  214. */
  215. noSuggestionText: 'No suggestions',
  216.  
  217. /**
  218. * The default placeholder text when nothing has been entered
  219. */
  220. placeholder: 'Type or click here',
  221.  
  222. /**
  223. * A function used to define how the items will be presented in the combo
  224. */
  225. renderer: null,
  226.  
  227. /**
  228. * Whether or not this field should be required
  229. */
  230. required: false,
  231.  
  232. /**
  233. * Set to true to render selection as a delimited string
  234. */
  235. resultAsString: false,
  236.  
  237. /**
  238. * Text delimiter to use in a delimited string.
  239. */
  240. resultAsStringDelimiter: ',',
  241.  
  242. /**
  243. * Name of JSON object property that represents the list of suggested objects
  244. */
  245. resultsField: 'results',
  246.  
  247. /**
  248. * A custom CSS class to add to a selected item
  249. */
  250. selectionCls: '',
  251.  
  252. /**
  253. * An optional element replacement in which the selection is rendered
  254. */
  255. selectionContainer: null,
  256.  
  257. /**
  258. * Where the selected items will be displayed. Only 'right', 'bottom' and 'inner' are valid values
  259. */
  260. selectionPosition: 'inner',
  261.  
  262. /**
  263. * A function used to define how the items will be presented in the tag list
  264. */
  265. selectionRenderer: null,
  266.  
  267. /**
  268. * Set to true to stack the selectioned items when positioned on the bottom
  269. * Requires the selectionPosition to be set to 'bottom'
  270. */
  271. selectionStacked: false,
  272.  
  273. /**
  274. * Direction used for sorting. Only 'asc' and 'desc' are valid values
  275. */
  276. sortDir: 'asc',
  277.  
  278. /**
  279. * name of JSON object property for local result sorting.
  280. * Leave null if you do not wish the results to be ordered or if they are already ordered remotely.
  281. */
  282. sortOrder: null,
  283.  
  284. /**
  285. * If set to true, suggestions will have to start by user input (and not simply contain it as a substring)
  286. */
  287. strictSuggest: false,
  288.  
  289. /**
  290. * Custom style added to the component container.
  291. */
  292. style: '',
  293.  
  294. /**
  295. * If set to true, the combo will expand / collapse when clicked upon
  296. */
  297. toggleOnClick: false,
  298.  
  299.  
  300. /**
  301. * Amount (in ms) between keyboard registers.
  302. */
  303. typeDelay: 400,
  304.  
  305. /**
  306. * If set to true, tab won't blur the component but will be registered as the ENTER key
  307. */
  308. useTabKey: false,
  309.  
  310. /**
  311. * If set to true, using comma will validate the user's choice
  312. */
  313. useCommaKey: true,
  314.  
  315.  
  316. /**
  317. * Determines whether or not the results will be displayed with a zebra table style
  318. */
  319. useZebraStyle: false,
  320.  
  321. /**
  322. * initial value for the field
  323. */
  324. value: null,
  325.  
  326. /**
  327. * name of JSON object property that represents its underlying value
  328. */
  329. valueField: 'id',
  330.  
  331. /**
  332. * regular expression to validate the values against
  333. */
  334. vregex: null,
  335.  
  336. /**
  337. * type to validate against
  338. */
  339. vtype: null

8.API方法。

  1. var instance = $('#example').magicSuggest({
  2. // options here
  3. });
  4.  
  5.  
  6. // adds items to the selection
  7. instance.addToSelection([object] objs, [boolean] silent)
  8.  
  9. // clears the selection
  10. instance.clear([boolean] silent)
  11.  
  12. // collapses the combo list
  13. instance.collapse([boolean] silent)
  14.  
  15. // disables the combo list
  16. instance.disable()
  17.  
  18. // removes what the user was typing
  19. instance.empty()
  20.  
  21. // enables the compolist
  22. instance.enable()
  23.  
  24. // expands the component
  25. instance.expand()
  26.  
  27. // returns the combo suggestions
  28. instance.getData()
  29.  
  30. // returns the status of the component
  31. instance.isDisabled()
  32.  
  33. // checks if the selection is valid
  34. instance.isValid()
  35.  
  36. // returns the list of extra URL paramaters set for AJAX requests
  37. instance.getDataUrlParams()
  38.  
  39. // returns the name used for HTML form submission
  40. instance.getName()
  41.  
  42. // returns an array of selected JSON objects
  43. instance.getSelection()
  44.  
  45. // returns the current text being entered by the user
  46. instance.getRawValue()
  47.  
  48. // returns an array containing only the selected JSON values
  49. instance.getValue()
  50.  
  51. // removes items from the selection
  52. instance.removeFromSelection([object] objs, [boolean] silent)
  53.  
  54. // sets the objects listed in the combo
  55. instance.setData([array] cbItems)
  56.  
  57. // sets the name to be used for form submission
  58. instance.setName([string] name)
  59.  
  60. // sets the selection with a given array of objects
  61. instance.setSelection(object[])
  62.  
  63. // sets the selection according to given values
  64. instance.setValue([array] ids)
  65.  
  66. // sets extra parameters for AJAX requests
  67. instance.setDataUrlParams([object] params)

9.事件。

  1. var instance = $('#example').magicSuggest({
  2. // options here
  3. });
  4.  
  5. instance.on( "beforeload", function(e, this) {
  6. // fired before the AJAX request is performed
  7. });
  8.  
  9. instance.on( "blur", function(e, this) {
  10. // fired when the component looses focus
  11. });
  12.  
  13. instance.on( "collapse", function(e, this) {
  14. // fired when the combo is collapsed
  15. });
  16.  
  17. instance.on( "expand", function(e, this) {
  18. // fired when the combo is expanded
  19. });
  20.  
  21. instance.on( "focus", function(e, this) {
  22. // fired when the combo gains focus
  23. });
  24.  
  25. instance.on( "keydown", function(e, this, keyevent) {
  26. // fired when the user presses a key
  27. });
  28.  
  29. instance.on( "keyup", function(e, this, keyevent) {
  30. // fired when the user releases a key
  31. });
  32.  
  33. instance.on( "load", function(e, this, records[]) {
  34. // fired when the AJAX request has been performed
  35. });
  36.  
  37. instance.on( "selectionchange", function(e, this, records[]) {
  38. // fired when the user has changed the selection
  39. });
  40.  
  41. instance.on( "triggerclick", function(e, this) {
  42. // fired when the user has changed the selection
  43. });

更新日志:

v2.1.6版本(2022-04-01)

  • 不清除为SHIFT触发关键帧设置事件的时间
  • 已修复:在输入时禁用任意HTML和SCRIPT执行。
  • 处理attr(“class”)未定义的情况

v2.1.5版本(2020-10-31)

  • 前置关闭按钮,而不是附加它。
  • 使用当前主代码更新了magicsuggest-min.js
  • 动态更新最大选择大小

2020-10-30

  • 已更新精简版

2020-10-15

  • 添加了一个功能,可以动态更新最大选择大小。它通过将列表向下截断到新的大小来处理比所选内容小的新大小。

2020-10-08

  • 准备关闭按钮而不是附加它

预览截图