bootstrap-5-autocomplete icon indicating copy to clipboard operation
bootstrap-5-autocomplete copied to clipboard

Bootstrap 5 Autocomplete returns null onSelectItem

Open awariat opened this issue 3 years ago • 2 comments

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.

awariat avatar May 20 '22 08:05 awariat

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');

M-Hadri avatar Jun 24 '22 13:06 M-Hadri

Fixed https://github.com/gch1p/bootstrap-5-autocomplete/pull/17

frugan-dev avatar Jul 02 '22 10:07 frugan-dev