From cafad2876febaf021c3903b036ca58a8a667712c Mon Sep 17 00:00:00 2001 From: Komunica Date: Mon, 27 Sep 2021 17:13:49 +0200 Subject: [PATCH] Add support for tags Converts a select with multiple attribute and `tags` option set to true, in a tags input: by searching for tags, if tag isn't in list user can add by hit Enter. --- js/bootstrap-select.js | 27 ++++++++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) diff --git a/js/bootstrap-select.js b/js/bootstrap-select.js index e7a8fb98c..d79e8ff8f 100644 --- a/js/bootstrap-select.js +++ b/js/bootstrap-select.js @@ -840,9 +840,14 @@ function showNoResults (searchMatch, searchValue) { if (!searchMatch.length) { - elementTemplates.noResults.innerHTML = this.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"'); - this.$menuInner[0].firstChild.appendChild(elementTemplates.noResults); + this.no_results = true; + if (!this.options.tags) { + elementTemplates.noResults.innerHTML = this.options.noneResultsText.replace('{0}', '"' + htmlEscape(searchValue) + '"'); + this.$menuInner[0].firstChild.appendChild(elementTemplates.noResults); + } + return; } + this.no_results = false; } function filterHidden (item) { @@ -963,7 +968,8 @@ display: false, sanitize: true, sanitizeFn: null, - whiteList: DefaultWhitelist + whiteList: DefaultWhitelist, + tags: false }; Selectpicker.prototype = { @@ -980,6 +986,8 @@ this.selectId = 'bs-select-' + selectId; element.classList.add('bs-select-hidden'); + + this.no_results = false; this.multiple = this.$element.prop('multiple'); this.autofocus = this.$element.prop('autofocus'); @@ -987,6 +995,10 @@ if (element.classList.contains('show-tick')) { this.options.showTick = true; } + + if (this.options.tags) { + this.options.liveSearch = true; + } this.$newElement = this.createDropdown(); @@ -3332,6 +3344,15 @@ that.$menuInner.find('.active a').trigger('click', true); // retain active class $this.trigger('focus'); + if (that.options.tags && e.which === keyCodes.ENTER && that.no_results) { + let searchValue = that.$searchbox[0].value; + let newOption = new Option(searchValue, searchValue); + newOption.selected = true; + that.$element[0].appendChild(newOption); + that.$searchbox[0].value = ''; + that.refresh(); + } + if (!that.options.liveSearch) { // Prevent screen from scrolling if the user hits the spacebar e.preventDefault();