From fb30170bc138ee2ec609927150ca8c33c378400d Mon Sep 17 00:00:00 2001 From: sp00n Date: Thu, 20 May 2021 22:41:03 +0200 Subject: Added the ability to set the label and value key names You can now set the names of the `label` and `value` keys in the options. They default to `label` and `value` to not break the current behavior, but you can also set them to `null`, so that you can use a simple object instead of an array of objects, just like in bootstrap-4-autocomplete. Examples: ``` const ac = new Autocomplete(field, { data: [{name: "entry1", text: "The first entry"}, {name: "entry2", text: "The second entry"}], label: "name", value: "text", onSelectItem: ({label, value}) => { console.log("user selected:", label, value); } }); const ac = new Autocomplete(field, { data: {entry1: "The first entry", entry2: "The second entry"}, label: null, value: null, onSelectItem: ({label, value}) => { console.log("user selected:", label, value); } }); ``` --- autocomplete.js | 17 +++++++++++++---- 1 file changed, 13 insertions(+), 4 deletions(-) diff --git a/autocomplete.js b/autocomplete.js index 7a9f151..016f8c3 100644 --- a/autocomplete.js +++ b/autocomplete.js @@ -3,6 +3,8 @@ const DEFAULTS = { maximumItems: 5, highlightTyped: true, highlightClass: 'text-primary', + label: 'label', + value: 'value' }; class Autocomplete { @@ -15,7 +17,7 @@ class Autocomplete { field.setAttribute('data-bs-toggle', 'dropdown'); field.classList.add('dropdown-toggle'); - const dropdown = ce(``); + const dropdown = ce(``); if (this.options.dropdownClass) dropdown.classList.add(this.options.dropdownClass); @@ -84,10 +86,17 @@ class Autocomplete { const items = this.field.nextSibling; items.innerHTML = ''; + const keys = Object.keys(this.options.data); + let count = 0; - for (let i = 0; i < this.options.data.length; i++) { - const {label, value} = this.options.data[i]; - const item = {label, value}; + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const entry = this.options.data[key]; + const item = { + label: this.options.label ? entry[this.options.label] : key, + value: this.options.value ? entry[this.options.value] : entry + }; + if (item.label.toLowerCase().indexOf(lookup.toLowerCase()) >= 0) { items.appendChild(this.createItem(lookup, item)); if (this.options.maximumItems > 0 && ++count >= this.options.maximumItems) -- cgit v1.2.3