tag-it.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542
  1. /*
  2. * jQuery UI Tag-it!
  3. *
  4. * @version v2.0 (06/2011)
  5. *
  6. * Copyright 2011, Levy Carneiro Jr.
  7. * Released under the MIT license.
  8. * http://aehlke.github.com/tag-it/LICENSE
  9. *
  10. * Homepage:
  11. * http://aehlke.github.com/tag-it/
  12. *
  13. * Authors:
  14. * Levy Carneiro Jr.
  15. * Martin Rehfeld
  16. * Tobias Schmidt
  17. * Skylar Challand
  18. * Alex Ehlke
  19. *
  20. * Maintainer:
  21. * Alex Ehlke - Twitter: @aehlke
  22. *
  23. * Dependencies:
  24. * jQuery v1.4+
  25. * jQuery UI v1.8+
  26. *
  27. * mod by Alexander Stifel
  28. */
  29. (function($) {
  30. $.widget('ui.tagit', {
  31. options: {
  32. allowDuplicates : false,
  33. caseSensitive : true,
  34. fieldName : 'tags',
  35. placeholderText : null, // Sets `placeholder` attr on input field.
  36. readOnly : false, // Disables editing.
  37. removeConfirmation: false, // Require confirmation to remove tags.
  38. tagLimit : null, // Max number of tags allowed (null for unlimited).
  39. // Used for autocomplete, unless you override `autocomplete.source`.
  40. availableTags : [],
  41. // Use to override or add any options to the autocomplete widget.
  42. //
  43. // By default, autocomplete.source will map to availableTags,
  44. // unless overridden.
  45. autocomplete: {},
  46. // Shows autocomplete before the user even types anything.
  47. showAutocompleteOnFocus: false,
  48. // When enabled, quotes are unneccesary for inputting multi-word tags.
  49. allowSpaces: false,
  50. // The below options are for using a single field instead of several
  51. // for our form values.
  52. //
  53. // When enabled, will use a single hidden field for the form,
  54. // rather than one per tag. It will delimit tags in the field
  55. // with singleFieldDelimiter.
  56. //
  57. // The easiest way to use singleField is to just instantiate tag-it
  58. // on an INPUT element, in which case singleField is automatically
  59. // set to true, and singleFieldNode is set to that element. This
  60. // way, you don't need to fiddle with these options.
  61. singleField: false,
  62. // This is just used when preloading data from the field, and for
  63. // populating the field with delimited tags as the user adds them.
  64. singleFieldDelimiter: ',',
  65. // Set this to an input DOM node to use an existing form field.
  66. // Any text in it will be erased on init. But it will be
  67. // populated with the text of tags as they are created,
  68. // delimited by singleFieldDelimiter.
  69. //
  70. // If this is not set, we create an input node for it,
  71. // with the name given in settings.fieldName.
  72. singleFieldNode: null,
  73. // Whether to animate tag removals or not.
  74. animate: true,
  75. // Optionally set a tabindex attribute on the input that gets
  76. // created for tag-it.
  77. tabIndex: null,
  78. // Event callbacks.
  79. beforeTagAdded : null,
  80. afterTagAdded : null,
  81. beforeTagRemoved : null,
  82. afterTagRemoved : null,
  83. onTagClicked : null,
  84. onTagLimitExceeded : null,
  85. // DEPRECATED:
  86. //
  87. // /!\ These event callbacks are deprecated and WILL BE REMOVED at some
  88. // point in the future. They're here for backwards-compatibility.
  89. // Use the above before/after event callbacks instead.
  90. onTagAdded : null,
  91. onTagRemoved: null,
  92. // `autocomplete.source` is the replacement for tagSource.
  93. tagSource: null
  94. // Do not use the above deprecated options.
  95. },
  96. _create: function() {
  97. // for handling static scoping inside callbacks
  98. var that = this;
  99. // There are 2 kinds of DOM nodes this widget can be instantiated on:
  100. // 1. UL, OL, or some element containing either of these.
  101. // 2. INPUT, in which case 'singleField' is overridden to true,
  102. // a UL is created and the INPUT is hidden.
  103. if (this.element.is('input')) {
  104. this.tagList = $('<ul></ul>').insertAfter(this.element);
  105. this.options.singleField = true;
  106. this.options.singleFieldNode = this.element;
  107. this.element.css('display', 'none');
  108. } else {
  109. this.tagList = this.element.find('ul, ol').andSelf().last();
  110. }
  111. this.tagInput = $('<input type="text" />').addClass('ui-widget-content');
  112. if (this.options.readOnly) this.tagInput.attr('disabled', 'disabled');
  113. if (this.options.tabIndex) {
  114. this.tagInput.attr('tabindex', this.options.tabIndex);
  115. }
  116. if (this.options.placeholderText) {
  117. this.tagInput.attr('placeholder', this.options.placeholderText);
  118. }
  119. if (!this.options.autocomplete.source) {
  120. this.options.autocomplete.source = function(search, showChoices) {
  121. var filter = search.term.toLowerCase();
  122. var choices = $.grep(this.options.availableTags, function(element) {
  123. // Only match autocomplete options that begin with the search term.
  124. // (Case insensitive.)
  125. return (element.toLowerCase().indexOf(filter) === 0);
  126. });
  127. if (!this.options.allowDuplicates) {
  128. choices = this._subtractArray(choices, this.assignedTags());
  129. }
  130. showChoices(choices);
  131. };
  132. }
  133. if (this.options.showAutocompleteOnFocus) {
  134. this.tagInput.focus(function(event, ui) {
  135. that._showAutocomplete();
  136. });
  137. if (typeof this.options.autocomplete.minLength === 'undefined') {
  138. this.options.autocomplete.minLength = 0;
  139. }
  140. }
  141. // Bind autocomplete.source callback functions to this context.
  142. if ($.isFunction(this.options.autocomplete.source)) {
  143. this.options.autocomplete.source = $.proxy(this.options.autocomplete.source, this);
  144. }
  145. // DEPRECATED.
  146. if ($.isFunction(this.options.tagSource)) {
  147. this.options.tagSource = $.proxy(this.options.tagSource, this);
  148. }
  149. this.tagList
  150. .addClass('tagit')
  151. .addClass('ui-widget ui-widget-content ui-corner-all')
  152. // Create the input field.
  153. .append($('<li class="tagit-new"></li>').append(this.tagInput))
  154. .click(function(e) {
  155. var target = $(e.target);
  156. if (target.hasClass('tagit-label')) {
  157. var tag = target.closest('.tagit-choice');
  158. if (!tag.hasClass('removed')) {
  159. that._trigger('onTagClicked', e, {tag: tag, tagLabel: that.tagLabel(tag)});
  160. }
  161. } else {
  162. // Sets the focus() to the input field, if the user
  163. // clicks anywhere inside the UL. This is needed
  164. // because the input field needs to be of a small size.
  165. that.tagInput.focus();
  166. }
  167. });
  168. // Single field support.
  169. var addedExistingFromSingleFieldNode = false;
  170. if (this.options.singleField) {
  171. if (this.options.singleFieldNode) {
  172. // Add existing tags from the input field.
  173. var node = $(this.options.singleFieldNode);
  174. var tags = node.val().split(this.options.singleFieldDelimiter);
  175. node.val('');
  176. $.each(tags, function(index, tag) {
  177. that.createTag(tag, null, true);
  178. addedExistingFromSingleFieldNode = true;
  179. });
  180. } else {
  181. // Create our single field input after our list.
  182. this.options.singleFieldNode = $('<input type="hidden" style="display:none;" value="" name="' + this.options.fieldName + '" />');
  183. this.tagList.after(this.options.singleFieldNode);
  184. }
  185. }
  186. // Add existing tags from the list, if any.
  187. if (!addedExistingFromSingleFieldNode) {
  188. this.tagList.children('li').each(function() {
  189. if (!$(this).hasClass('tagit-new')) {
  190. that.createTag($(this).text(), $(this).attr('class'), true);
  191. $(this).remove();
  192. }
  193. });
  194. }
  195. // Events.
  196. this.tagInput
  197. .keydown(function(event) {
  198. // Backspace is not detected within a keypress, so it must use keydown.
  199. if (event.which == $.ui.keyCode.BACKSPACE && that.tagInput.val() === '') {
  200. var tag = that._lastTag();
  201. if (!that.options.removeConfirmation || tag.hasClass('remove')) {
  202. // When backspace is pressed, the last tag is deleted.
  203. that.removeTag(tag);
  204. } else if (that.options.removeConfirmation) {
  205. tag.addClass('remove ui-state-highlight');
  206. }
  207. } else if (that.options.removeConfirmation) {
  208. that._lastTag().removeClass('remove ui-state-highlight');
  209. }
  210. // Comma/Space/Enter are all valid delimiters for new tags,
  211. // except when there is an open quote or if setting allowSpaces = true.
  212. // Tab will also create a tag, unless the tag input is empty,
  213. // in which case it isn't caught.
  214. if (
  215. event.which === $.ui.keyCode.COMMA ||
  216. event.which === $.ui.keyCode.ENTER ||
  217. (
  218. event.which == $.ui.keyCode.TAB &&
  219. that.tagInput.val() !== ''
  220. ) ||
  221. (
  222. event.which == $.ui.keyCode.SPACE &&
  223. that.options.allowSpaces !== true &&
  224. (
  225. $.trim(that.tagInput.val()).replace( /^s*/, '' ).charAt(0) != '"' ||
  226. (
  227. $.trim(that.tagInput.val()).charAt(0) == '"' &&
  228. $.trim(that.tagInput.val()).charAt($.trim(that.tagInput.val()).length - 1) == '"' &&
  229. $.trim(that.tagInput.val()).length - 1 !== 0
  230. )
  231. )
  232. )
  233. ) {
  234. // Enter submits the form if there's no text in the input.
  235. if (!(event.which === $.ui.keyCode.ENTER && that.tagInput.val() === '')) {
  236. event.preventDefault();
  237. }
  238. that.createTag(that._cleanedInput());
  239. // The autocomplete doesn't close automatically when TAB is pressed.
  240. // So let's ensure that it closes.
  241. that.tagInput.autocomplete('close');
  242. }
  243. }).blur(function(e){
  244. // Create a tag when the element loses focus.
  245. // If autocomplete is enabled and suggestion was clicked, don't add it.
  246. if (!that.tagInput.data('autocomplete-open')) {
  247. that.createTag(that._cleanedInput());
  248. }
  249. });
  250. // Autocomplete.
  251. if (this.options.availableTags || this.options.tagSource || this.options.autocomplete.source) {
  252. var autocompleteOptions = {
  253. select: function(event, ui) {
  254. that.createTag(ui.item.value);
  255. // Preventing the tag input to be updated with the chosen value.
  256. return false;
  257. }
  258. };
  259. $.extend(autocompleteOptions, this.options.autocomplete);
  260. // tagSource is deprecated, but takes precedence here since autocomplete.source is set by default,
  261. // while tagSource is left null by default.
  262. autocompleteOptions.source = this.options.tagSource || autocompleteOptions.source;
  263. this.tagInput.autocomplete(autocompleteOptions).bind('autocompleteopen', function(event, ui) {
  264. that.tagInput.data('autocomplete-open', true);
  265. }).bind('autocompleteclose', function(event, ui) {
  266. that.tagInput.data('autocomplete-open', false)
  267. });
  268. }
  269. },
  270. _cleanedInput: function() {
  271. // Returns the contents of the tag input, cleaned and ready to be passed to createTag
  272. return $.trim(this.tagInput.val().replace(/^"(.*)"$/, '$1'));
  273. },
  274. _lastTag: function() {
  275. return this.tagList.find('.tagit-choice:last:not(.removed)');
  276. },
  277. _tags: function() {
  278. return this.tagList.find('.tagit-choice:not(.removed)');
  279. },
  280. assignedTags: function() {
  281. // Returns an array of tag string values
  282. var that = this;
  283. var tags = [];
  284. if (this.options.singleField) {
  285. tags = $(this.options.singleFieldNode).val().split(this.options.singleFieldDelimiter);
  286. if (tags[0] === '') {
  287. tags = [];
  288. }
  289. } else {
  290. this._tags().each(function() {
  291. tags.push(that.tagLabel(this));
  292. });
  293. }
  294. return tags;
  295. },
  296. _updateSingleTagsField: function(tags) {
  297. // Takes a list of tag string values, updates this.options.singleFieldNode.val to the tags delimited by this.options.singleFieldDelimiter
  298. $(this.options.singleFieldNode).val(tags.join(this.options.singleFieldDelimiter)).trigger('change');
  299. },
  300. _subtractArray: function(a1, a2) {
  301. var result = [];
  302. for (var i = 0; i < a1.length; i++) {
  303. if ($.inArray(a1[i], a2) == -1) {
  304. result.push(a1[i]);
  305. }
  306. }
  307. return result;
  308. },
  309. tagLabel: function(tag) {
  310. // Returns the tag's string label.
  311. if (this.options.singleField) {
  312. return $(tag).find('.tagit-label:first').text();
  313. } else {
  314. return $(tag).find('input:first').val();
  315. }
  316. },
  317. _showAutocomplete: function() {
  318. this.tagInput.autocomplete('search', '');
  319. },
  320. _findTagByLabel: function(name) {
  321. var that = this;
  322. var tag = null;
  323. this._tags().each(function(i) {
  324. if (that._formatStr(name) == that._formatStr(that.tagLabel(this))) {
  325. tag = $(this);
  326. return false;
  327. }
  328. });
  329. return tag;
  330. },
  331. _isNew: function(name) {
  332. return !this._findTagByLabel(name);
  333. },
  334. _formatStr: function(str) {
  335. if (this.options.caseSensitive) {
  336. return str;
  337. }
  338. return $.trim(str.toLowerCase());
  339. },
  340. _effectExists: function(name) {
  341. return Boolean($.effects && ($.effects[name] || ($.effects.effect && $.effects.effect[name])));
  342. },
  343. createTag: function(value, additionalClass, duringInitialization) {
  344. var that = this;
  345. value = $.trim(value);
  346. if(this.options.preprocessTag) {
  347. value = this.options.preprocessTag(value);
  348. }
  349. if (value === '') {
  350. return false;
  351. }
  352. if (!this.options.allowDuplicates && !this._isNew(value)) {
  353. var existingTag = this._findTagByLabel(value);
  354. if (this._trigger('onTagExists', null, {
  355. existingTag: existingTag,
  356. duringInitialization: duringInitialization
  357. }) !== false) {
  358. if (this._effectExists('highlight')) {
  359. existingTag.effect('highlight');
  360. }
  361. }
  362. return false;
  363. }
  364. if (this.options.tagLimit && this._tags().length >= this.options.tagLimit) {
  365. this._trigger('onTagLimitExceeded', null, {duringInitialization: duringInitialization});
  366. return false;
  367. }
  368. var label = $(this.options.onTagClicked ? '<a class="tagit-label"></a>' : '<span class="tagit-label"></span>').text(value);
  369. // Create tag.
  370. var tag = $('<li></li>')
  371. .addClass('tagit-choice ui-widget-content ui-state-default ui-corner-all')
  372. .addClass(additionalClass)
  373. .append(label);
  374. if (this.options.readOnly){
  375. tag.addClass('tagit-choice-read-only');
  376. } else {
  377. tag.addClass('tagit-choice-editable');
  378. // Button for removing the tag.
  379. var removeTagIcon = $('<span></span>')
  380. .addClass('ui-icon ui-icon-close');
  381. var removeTag = $('<a><span class="text-icon">\xd7</span></a>') // \xd7 is an X
  382. .addClass('tagit-close')
  383. .append(removeTagIcon)
  384. .click(function(e) {
  385. // Removes a tag when the little 'x' is clicked.
  386. that.removeTag(tag);
  387. });
  388. tag.append(removeTag);
  389. }
  390. // Unless options.singleField is set, each tag has a hidden input field inline.
  391. if (!this.options.singleField) {
  392. var escapedValue = label.html();
  393. tag.append('<input type="hidden" style="display:none;" value="' + escapedValue + '" name="' + this.options.fieldName + '" />');
  394. }
  395. if (this._trigger('beforeTagAdded', null, {
  396. tag: tag,
  397. tagLabel: this.tagLabel(tag),
  398. duringInitialization: duringInitialization
  399. }) === false) {
  400. return;
  401. }
  402. if (this.options.singleField) {
  403. var tags = this.assignedTags();
  404. tags.push(value);
  405. this._updateSingleTagsField(tags);
  406. }
  407. // DEPRECATED.
  408. this._trigger('onTagAdded', null, tag);
  409. this.tagInput.val('');
  410. // Insert tag.
  411. this.tagInput.parent().before(tag);
  412. this._trigger('afterTagAdded', null, {
  413. tag: tag,
  414. tagLabel: this.tagLabel(tag),
  415. duringInitialization: duringInitialization
  416. });
  417. if (this.options.showAutocompleteOnFocus && !duringInitialization) {
  418. setTimeout(function () { that._showAutocomplete(); }, 0);
  419. }
  420. },
  421. removeTag: function(tag, animate) {
  422. animate = typeof animate === 'undefined' ? this.options.animate : animate;
  423. tag = $(tag);
  424. // DEPRECATED.
  425. this._trigger('onTagRemoved', null, tag);
  426. if (this._trigger('beforeTagRemoved', null, {tag: tag, tagLabel: this.tagLabel(tag)}) === false) {
  427. return;
  428. }
  429. if (this.options.singleField) {
  430. var tags = this.assignedTags();
  431. var removedTagLabel = this.tagLabel(tag);
  432. tags = $.grep(tags, function(el){
  433. return el != removedTagLabel;
  434. });
  435. this._updateSingleTagsField(tags);
  436. }
  437. if (animate) {
  438. tag.addClass('removed'); // Excludes this tag from _tags.
  439. var hide_args = this._effectExists('blind') ? ['blind', {direction: 'horizontal'}, 'fast'] : ['fast'];
  440. var thisTag = this;
  441. hide_args.push(function() {
  442. tag.remove();
  443. thisTag._trigger('afterTagRemoved', null, {tag: tag, tagLabel: thisTag.tagLabel(tag)});
  444. });
  445. tag.fadeOut('fast').hide.apply(tag, hide_args).dequeue();
  446. } else {
  447. tag.remove();
  448. this._trigger('afterTagRemoved', null, {tag: tag, tagLabel: this.tagLabel(tag)});
  449. }
  450. },
  451. removeTagByLabel: function(tagLabel, animate) {
  452. var toRemove = this._findTagByLabel(tagLabel);
  453. if (!toRemove) {
  454. throw "No such tag exists with the name '" + tagLabel + "'";
  455. }
  456. this.removeTag(toRemove, animate);
  457. },
  458. removeAll: function() {
  459. // Removes all tags.
  460. var that = this;
  461. this._tags().each(function(index, tag) {
  462. that.removeTag(tag, false);
  463. });
  464. }
  465. });
  466. })(jQuery);