aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorsp00n <sp.00.n@gmx.net>2021-05-20 22:41:03 +0200
committerGitHub <noreply@github.com>2021-05-20 22:41:03 +0200
commitfb30170bc138ee2ec609927150ca8c33c378400d (patch)
tree7c7ba79ae1079d29032fa69bbaeaf210141acb78
parentdbca6d0a995b2a66a30ace2c4e6e777411594b08 (diff)
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); } }); ```
-rw-r--r--autocomplete.js17
1 files 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(`<div class="dropdown-menu" ></div>`);
+ const dropdown = ce(`<div class="dropdown-menu"></div>`);
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)