tagsinput.js 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654
  1. /*
  2. * bootstrap-tagsinput v0.8.0
  3. *
  4. * For details, see the web site: https://github.com/bootstrap-tagsinput/bootstrap-tagsinput
  5. */
  6. (function ($) {
  7. "use strict";
  8. var defaultOptions = {
  9. tagClass: function (item) {
  10. return 'label label-info';
  11. },
  12. focusClass: 'focus',
  13. itemValue: function (item) {
  14. return item ? item.toString() : item;
  15. },
  16. itemText: function (item) {
  17. return this.itemValue(item);
  18. },
  19. itemTitle: function (item) {
  20. return null;
  21. },
  22. freeInput: true,
  23. addOnBlur: true,
  24. maxTags: undefined,
  25. maxChars: undefined,
  26. confirmKeys: [13, 44],
  27. delimiter: ',',
  28. inputMinWidth: 80,
  29. delimiterRegex: null,
  30. cancelConfirmKeysOnEmpty: false,
  31. onTagExists: function (item, $tag) {
  32. $tag.hide().fadeIn();
  33. },
  34. trimValue: false,
  35. allowDuplicates: false,
  36. triggerChange: true
  37. };
  38. /**
  39. * Constructor function
  40. */
  41. function TagsInput(element, options) {
  42. this.isInit = true;
  43. this.itemsArray = [];
  44. this.$element = $(element);
  45. this.$element.hide();
  46. this.isSelect = (element.tagName === 'SELECT');
  47. this.multiple = (this.isSelect && element.hasAttribute('multiple'));
  48. this.objectItems = options && options.itemValue;
  49. this.placeholderText = element.hasAttribute('placeholder') ? this.$element.attr('placeholder') : '';
  50. this.inputSize = Math.max(1, this.placeholderText.length);
  51. this.$container = $('<div class="bootstrap-tagsinput"></div>');
  52. this.$input = $('<input type="text" placeholder="' + this.placeholderText + '"/>').appendTo(this.$container);
  53. this.$element.before(this.$container);
  54. this.build(options);
  55. this.isInit = false;
  56. }
  57. TagsInput.prototype = {
  58. constructor: TagsInput,
  59. /**
  60. * Adds the given item as a new tag. Pass true to dontPushVal to prevent
  61. * updating the elements val()
  62. */
  63. add: function (item, dontPushVal, options) {
  64. var self = this;
  65. if (self.options.maxTags && self.itemsArray.length >= self.options.maxTags)
  66. return;
  67. // Ignore falsey values, except false
  68. if (item !== false && !item)
  69. return;
  70. // Trim value
  71. if (typeof item === "string" && self.options.trimValue) {
  72. item = $.trim(item);
  73. }
  74. // Throw an error when trying to add an object while the itemValue option was not set
  75. if (typeof item === "object" && !self.objectItems)
  76. throw("Can't add objects when itemValue option is not set");
  77. // Ignore strings only containg whitespace
  78. if (item.toString().match(/^\s*$/))
  79. return;
  80. // If SELECT but not multiple, remove current tag
  81. if (self.isSelect && !self.multiple && self.itemsArray.length > 0)
  82. self.remove(self.itemsArray[0]);
  83. if (typeof item === "string" && this.$element[0].tagName === 'INPUT') {
  84. var delimiter = (self.options.delimiterRegex) ? self.options.delimiterRegex : self.options.delimiter;
  85. var items = item.split(delimiter);
  86. if (items.length > 1) {
  87. for (var i = 0; i < items.length; i++) {
  88. this.add(items[i], true);
  89. }
  90. if (!dontPushVal)
  91. self.pushVal(self.options.triggerChange);
  92. return;
  93. }
  94. }
  95. var itemValue = self.options.itemValue(item),
  96. itemText = self.options.itemText(item),
  97. tagClass = self.options.tagClass(item),
  98. itemTitle = self.options.itemTitle(item);
  99. // Ignore items allready added
  100. var existing = $.grep(self.itemsArray, function (item) {
  101. return self.options.itemValue(item) === itemValue;
  102. })[0];
  103. if (existing && !self.options.allowDuplicates) {
  104. // Invoke onTagExists
  105. if (self.options.onTagExists) {
  106. var $existingTag = $(".tag", self.$container).filter(function () {
  107. return $(this).data("item") === existing;
  108. });
  109. self.options.onTagExists(item, $existingTag);
  110. }
  111. return;
  112. }
  113. // if length greater than limit
  114. if (self.items().toString().length + item.length + 1 > self.options.maxInputLength)
  115. return;
  116. // raise beforeItemAdd arg
  117. var beforeItemAddEvent = $.Event('beforeItemAdd', {item: item, cancel: false, options: options});
  118. self.$element.trigger(beforeItemAddEvent);
  119. if (beforeItemAddEvent.cancel)
  120. return;
  121. // register item in internal array and map
  122. self.itemsArray.push(item);
  123. // add a tag element
  124. var $tag = $('<span class="tag ' + htmlEncode(tagClass) + (itemTitle !== null ? ('" title="' + itemTitle) : '') + '">' + htmlEncode(itemText) + '<span data-role="remove"></span></span>');
  125. $tag.data('item', item);
  126. self.findInputWrapper().before($tag);
  127. $tag.after(' ');
  128. // Check to see if the tag exists in its raw or uri-encoded form
  129. var optionExists = (
  130. $('option[value="' + encodeURIComponent(itemValue) + '"]', self.$element).length ||
  131. $('option[value="' + htmlEncode(itemValue) + '"]', self.$element).length
  132. );
  133. // add <option /> if item represents a value not present in one of the <select />'s options
  134. if (self.isSelect && !optionExists) {
  135. var $option = $('<option selected>' + htmlEncode(itemText) + '</option>');
  136. $option.data('item', item);
  137. $option.attr('value', itemValue);
  138. self.$element.append($option);
  139. }
  140. if (!dontPushVal)
  141. self.pushVal(self.options.triggerChange);
  142. // Add class when reached maxTags
  143. if (self.options.maxTags === self.itemsArray.length || self.items().toString().length === self.options.maxInputLength)
  144. self.$container.addClass('bootstrap-tagsinput-max');
  145. // If using autocomplete, once the tag has been added, clear the autocomplete value so it does not stick around in the input.
  146. if (self.options.autocomplete) {
  147. // self.$input.autocomplete('clear');
  148. }
  149. if (this.isInit) {
  150. self.$element.trigger($.Event('itemAddedOnInit', {item: item, options: options}));
  151. } else {
  152. self.$element.trigger($.Event('itemAdded', {item: item, options: options}));
  153. }
  154. },
  155. /**
  156. * Removes the given item. Pass true to dontPushVal to prevent updating the
  157. * elements val()
  158. */
  159. remove: function (item, dontPushVal, options) {
  160. var self = this;
  161. if (self.objectItems) {
  162. if (typeof item === "object")
  163. item = $.grep(self.itemsArray, function (other) {
  164. return self.options.itemValue(other) == self.options.itemValue(item);
  165. });
  166. else
  167. item = $.grep(self.itemsArray, function (other) {
  168. return self.options.itemValue(other) == item;
  169. });
  170. item = item[item.length - 1];
  171. }
  172. if (item) {
  173. var beforeItemRemoveEvent = $.Event('beforeItemRemove', {item: item, cancel: false, options: options});
  174. self.$element.trigger(beforeItemRemoveEvent);
  175. if (beforeItemRemoveEvent.cancel)
  176. return;
  177. $('.tag', self.$container).filter(function () {
  178. return $(this).data('item') === item;
  179. }).remove();
  180. $('option', self.$element).filter(function () {
  181. return $(this).data('item') === item;
  182. }).remove();
  183. if ($.inArray(item, self.itemsArray) !== -1)
  184. self.itemsArray.splice($.inArray(item, self.itemsArray), 1);
  185. }
  186. if (!dontPushVal)
  187. self.pushVal(self.options.triggerChange);
  188. // Remove class when reached maxTags
  189. if (self.options.maxTags > self.itemsArray.length)
  190. self.$container.removeClass('bootstrap-tagsinput-max');
  191. self.$element.trigger($.Event('itemRemoved', {item: item, options: options}));
  192. },
  193. /**
  194. * Removes all items
  195. */
  196. removeAll: function () {
  197. var self = this;
  198. $('.tag', self.$container).remove();
  199. $('option', self.$element).remove();
  200. while (self.itemsArray.length > 0)
  201. self.itemsArray.pop();
  202. self.pushVal(self.options.triggerChange);
  203. },
  204. /**
  205. * Refreshes the tags so they match the text/value of their corresponding
  206. * item.
  207. */
  208. refresh: function () {
  209. var self = this;
  210. $('.tag', self.$container).each(function () {
  211. var $tag = $(this),
  212. item = $tag.data('item'),
  213. itemValue = self.options.itemValue(item),
  214. itemText = self.options.itemText(item),
  215. tagClass = self.options.tagClass(item);
  216. // Update tag's class and inner text
  217. $tag.attr('class', null);
  218. $tag.addClass('tag ' + htmlEncode(tagClass));
  219. $tag.contents().filter(function () {
  220. return this.nodeType == 3;
  221. })[0].nodeValue = htmlEncode(itemText);
  222. if (self.isSelect) {
  223. var option = $('option', self.$element).filter(function () {
  224. return $(this).data('item') === item;
  225. });
  226. option.attr('value', itemValue);
  227. }
  228. });
  229. },
  230. /**
  231. * Returns the items added as tags
  232. */
  233. items: function () {
  234. return this.itemsArray;
  235. },
  236. /**
  237. * Assembly value by retrieving the value of each item, and set it on the
  238. * element.
  239. */
  240. pushVal: function () {
  241. var self = this,
  242. val = $.map(self.items(), function (item) {
  243. return self.options.itemValue(item).toString();
  244. });
  245. self.$element.val(val, true);
  246. if (self.options.triggerChange)
  247. self.$element.trigger('change');
  248. },
  249. /**
  250. * Initializes the tags input behaviour on the element
  251. */
  252. build: function (options) {
  253. var self = this;
  254. self.options = $.extend({}, defaultOptions, options);
  255. // When itemValue is set, freeInput should always be false
  256. if (self.objectItems)
  257. self.options.freeInput = false;
  258. makeOptionItemFunction(self.options, 'itemValue');
  259. makeOptionItemFunction(self.options, 'itemText');
  260. makeOptionFunction(self.options, 'tagClass');
  261. if (self.options.autocomplete) {
  262. var autocomplete = self.options.autocomplete || {};
  263. // makeOptionFunction(autocomplete, 'lookup');
  264. self.$input.autocomplete($.extend(true, {}, {
  265. type: 'post',
  266. params: function (q) {
  267. var params = {};
  268. params['name'] = self.$element.prop("name");
  269. params['tags'] = self.$element.val();
  270. return params;
  271. },
  272. onSelect: function (suggestion) {
  273. self.add(suggestion.value);
  274. self.$input.val('').width(self.options.inputMinWidth).focus();
  275. }
  276. }, autocomplete));
  277. }
  278. self.$container.on('click', $.proxy(function (event) {
  279. if (!self.$element.attr('disabled')) {
  280. self.$input.removeAttr('disabled');
  281. }
  282. self.$input.focus();
  283. if (self.options.autocomplete && self.$input.autocomplete().visible) {
  284. clearTimeout(self.$input.autocomplete().blurTimeoutId);
  285. }
  286. }, self));
  287. if (self.options.addOnBlur && self.options.freeInput) {
  288. self.$input.on('focusout', $.proxy(function (event) {
  289. // HACK: only process on focusout when no autocomplete opened, to
  290. // avoid adding the autocomplete text as tag
  291. if (!self.options.autocomplete) {
  292. self.add(self.$input.val());
  293. self.$input.val('').css("width", self.options.inputMinWidth);
  294. } else {
  295. var autocomplete = self.$input.autocomplete();
  296. setTimeout(function () {
  297. if (!autocomplete.visible && self.$input.val() !== '') {
  298. self.add(self.$input.val());
  299. self.$input.val('').css("width", self.options.inputMinWidth);
  300. }
  301. }, 210);
  302. }
  303. }, self));
  304. }
  305. // Toggle the 'focus' css class on the container when it has focus
  306. self.$container.on({
  307. focusin: function () {
  308. self.$container.addClass(self.options.focusClass);
  309. },
  310. focusout: function () {
  311. self.$container.removeClass(self.options.focusClass);
  312. },
  313. });
  314. self.$container.on('keydown', 'input', $.proxy(function (event) {
  315. var $input = $(event.target),
  316. $inputWrapper = self.findInputWrapper();
  317. if (self.$element.attr('disabled')) {
  318. self.$input.attr('disabled', 'disabled');
  319. return;
  320. }
  321. switch (event.which) {
  322. // BACKSPACE
  323. case 8:
  324. if (doGetCaretPosition($input[0]) === 0) {
  325. var prev = $inputWrapper.prev();
  326. if (prev.length) {
  327. self.remove(prev.data('item'));
  328. }
  329. }
  330. break;
  331. // DELETE
  332. case 46:
  333. if (doGetCaretPosition($input[0]) === 0) {
  334. var next = $inputWrapper.next();
  335. if (next.length) {
  336. self.remove(next.data('item'));
  337. }
  338. }
  339. break;
  340. // LEFT ARROW
  341. case 37:
  342. // Try to move the input before the previous tag
  343. var $prevTag = $inputWrapper.prev();
  344. if ($input.val().length === 0 && $prevTag[0]) {
  345. $prevTag.before($inputWrapper);
  346. $input.focus();
  347. }
  348. break;
  349. // RIGHT ARROW
  350. case 39:
  351. // Try to move the input after the next tag
  352. var $nextTag = $inputWrapper.next();
  353. if ($input.val().length === 0 && $nextTag[0]) {
  354. $nextTag.after($inputWrapper);
  355. $input.focus();
  356. }
  357. break;
  358. default:
  359. // ignore
  360. }
  361. $input.css('width', self.getInputTextWidth());
  362. }, self));
  363. self.$container.on('keypress', 'input', $.proxy(function (event) {
  364. var $input = $(event.target);
  365. if (self.$element.attr('disabled')) {
  366. self.$input.attr('disabled', 'disabled');
  367. return;
  368. }
  369. var text = $input.val(),
  370. maxLengthReached = self.options.maxChars && text.length >= self.options.maxChars;
  371. if (self.options.freeInput && (keyCombinationInList(event, self.options.confirmKeys) || maxLengthReached)) {
  372. // Only attempt to add a tag if there is data in the field
  373. if (text.length !== 0) {
  374. self.add(maxLengthReached ? text.substr(0, self.options.maxChars) : text);
  375. $input.val('').css("width", self.options.inputMinWidth);
  376. }
  377. // If the field is empty, let the event triggered fire as usual
  378. if (self.options.cancelConfirmKeysOnEmpty === false) {
  379. event.preventDefault();
  380. }
  381. }
  382. $input.css('width', self.getInputTextWidth());
  383. }, self));
  384. // Remove icon clicked
  385. self.$container.on('click', '[data-role=remove]', $.proxy(function (event) {
  386. if (self.$element.attr('disabled')) {
  387. return;
  388. }
  389. self.remove($(event.target).closest('.tag').data('item'));
  390. }, self));
  391. // Only add existing value as tags when using strings as tags
  392. if (self.options.itemValue === defaultOptions.itemValue) {
  393. if (self.$element[0].tagName === 'INPUT') {
  394. self.add(self.$element.val());
  395. } else {
  396. $('option', self.$element).each(function () {
  397. self.add($(this).attr('value'), true);
  398. });
  399. }
  400. }
  401. },
  402. /**
  403. * Removes all tagsinput behaviour and unregsiter all event handlers
  404. */
  405. destroy: function () {
  406. var self = this;
  407. // Unbind events
  408. self.$container.off('keypress', 'input');
  409. self.$container.off('click', '[role=remove]');
  410. self.$container.remove();
  411. self.$element.removeData('tagsinput');
  412. self.$element.show();
  413. },
  414. /**
  415. * Sets focus on the tagsinput
  416. */
  417. focus: function () {
  418. this.$input.focus();
  419. },
  420. /**
  421. * Returns the internal input element
  422. */
  423. input: function () {
  424. return this.$input;
  425. },
  426. /**
  427. * Returns the element which is wrapped around the internal input. This
  428. * is normally the $container, but typeahead.js moves the $input element.
  429. */
  430. findInputWrapper: function () {
  431. var elt = this.$input[0],
  432. container = this.$container[0];
  433. while (elt && elt.parentNode !== container)
  434. elt = elt.parentNode;
  435. return $(elt);
  436. },
  437. /**
  438. * Get input text width
  439. * @returns {number}
  440. */
  441. getInputTextWidth: function () {
  442. var $input = this.$input;
  443. var self = this;
  444. var msgspan = $input.next().length > 0 ? $input.next() : $("<span />").addClass("tagsinput-text").insertAfter($input);
  445. var textWidth = msgspan.text($input.val()).outerWidth();
  446. textWidth = Math.max(textWidth, self.options.inputMinWidth);
  447. textWidth = Math.min(textWidth, self.$container.innerWidth());
  448. return textWidth;
  449. }
  450. };
  451. /**
  452. * Register JQuery plugin
  453. */
  454. $.fn.tagsinput = function (arg1, arg2, arg3) {
  455. var results = [];
  456. this.each(function () {
  457. var tagsinput = $(this).data('tagsinput');
  458. // Initialize a new tags input
  459. if (!tagsinput) {
  460. tagsinput = new TagsInput(this, $.extend(true, {}, arg1, $(this).data('tagsinput-options') || {}));
  461. $(this).data('tagsinput', tagsinput);
  462. results.push(tagsinput);
  463. if (this.tagName === 'SELECT') {
  464. $('option', $(this)).attr('selected', 'selected');
  465. }
  466. // Init tags from $(this).val()
  467. $(this).val($(this).val());
  468. } else if (!arg1 && !arg2) {
  469. // tagsinput already exists
  470. // no function, trying to init
  471. results.push(tagsinput);
  472. } else if (tagsinput[arg1] !== undefined) {
  473. // Invoke function on existing tags input
  474. if (tagsinput[arg1].length === 3 && arg3 !== undefined) {
  475. var retVal = tagsinput[arg1](arg2, null, arg3);
  476. } else {
  477. var retVal = tagsinput[arg1](arg2);
  478. }
  479. if (retVal !== undefined)
  480. results.push(retVal);
  481. }
  482. });
  483. return results.length > 1 ? results : results[0];
  484. };
  485. $.fn.tagsinput.Constructor = TagsInput;
  486. /**
  487. * Most options support both a string or number as well as a function as
  488. * option value. This function makes sure that the option with the given
  489. * key in the given options is wrapped in a function
  490. */
  491. function makeOptionItemFunction(options, key) {
  492. if (typeof options[key] !== 'function') {
  493. var propertyName = options[key];
  494. options[key] = function (item) {
  495. return item[propertyName];
  496. };
  497. }
  498. }
  499. function makeOptionFunction(options, key) {
  500. if (typeof options[key] !== 'function') {
  501. var value = options[key];
  502. options[key] = function () {
  503. return value;
  504. };
  505. }
  506. }
  507. /**
  508. * HtmlEncodes the given value
  509. */
  510. var htmlEncodeContainer = $('<div />');
  511. function htmlEncode(value) {
  512. if (value) {
  513. return htmlEncodeContainer.text(value).html();
  514. } else {
  515. return '';
  516. }
  517. }
  518. /**
  519. * Returns the position of the caret in the given input field
  520. * http://flightschool.acylt.com/devnotes/caret-position-woes/
  521. */
  522. function doGetCaretPosition(oField) {
  523. var iCaretPos = 0;
  524. if (document.selection) {
  525. oField.focus();
  526. var oSel = document.selection.createRange();
  527. oSel.moveStart('character', -oField.value.length);
  528. iCaretPos = oSel.text.length;
  529. } else if (oField.selectionStart || oField.selectionStart == '0') {
  530. iCaretPos = oField.selectionStart;
  531. }
  532. return (iCaretPos);
  533. }
  534. /**
  535. * Returns boolean indicates whether user has pressed an expected key combination.
  536. * @param object keyPressEvent: JavaScript event object, refer
  537. * http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
  538. * @param object lookupList: expected key combinations, as in:
  539. * [13, {which: 188, shiftKey: true}]
  540. */
  541. function keyCombinationInList(keyPressEvent, lookupList) {
  542. var found = false;
  543. $.each(lookupList, function (index, keyCombination) {
  544. if (typeof (keyCombination) === 'number' && keyPressEvent.which === keyCombination) {
  545. found = true;
  546. return false;
  547. }
  548. if (keyPressEvent.which === keyCombination.which) {
  549. var alt = !keyCombination.hasOwnProperty('altKey') || keyPressEvent.altKey === keyCombination.altKey,
  550. shift = !keyCombination.hasOwnProperty('shiftKey') || keyPressEvent.shiftKey === keyCombination.shiftKey,
  551. ctrl = !keyCombination.hasOwnProperty('ctrlKey') || keyPressEvent.ctrlKey === keyCombination.ctrlKey;
  552. if (alt && shift && ctrl) {
  553. found = true;
  554. return false;
  555. }
  556. }
  557. });
  558. return found;
  559. }
  560. })(window.jQuery);