bootstrap-5-autocomplete
bootstrap-5-autocomplete copied to clipboard
Bootstrap 5 Autocomplete returns null onSelectItem
Hi. How are you. Nice code but sometimes it returns null my code:
async function getProductsArray() {
let autoCompleteArray = [];
try {
const [productsArray, productsDefault] = await getSettingsProducts();
productsArray.sort();
productsArray.forEach((element, index) => {
autoCompleteArray.push({
label: element,
value: element
});
});
const field = document.getElementById('productsAutoComplete');
const ac = new Autocomplete(field, {
//data: [{label: "I'm a label", value: 42}],
data: autoCompleteArray,
maximumItems: 5,
threshold: 1,
onSelectItem: ({
label,
value
}) => {
console.log("user selected:", label, value);//<--------sometimes null null
document.getElementById('productsAutoComplete').value = "";
inputVal(label);
}
});
} catch (error) {
console.log("Get Products Error: ", error);
// errorInfo(error)
}
}
It looks like it works, but not always. Sometimes "onSelectItem" returns "null"(about 25%). Even if the same element is clicked. I checked on chrome and Firefox. On Chrome, a bit better.
just replace this 2 lines in autocomplete.js ( function createItems )..
replace :
let dataLabel = e.target.getAttribute('data-label');
let dataValue = e.target.getAttribute('data-value');
with :
let dataLabel = e.currentTarget.getAttribute('data-label');
let dataValue = e.currentTarget.getAttribute('data-value');
or
let dataLabel = e.target.getAttribute('data-label') || e.target.parentNode.getAttribute('data-label');
let dataValue = e.target.getAttribute('data-value') || e.target.parentNode.getAttribute('data-value');
Fixed https://github.com/gch1p/bootstrap-5-autocomplete/pull/17