'my function in jquery not working correctly but fine in simple JS

this code is for auto-complete search

clicked topic is not showing in search-input-box

$(function () {
  let s = ["aa", "abb", "acc", "adf"],
    search = document.querySelector(".search"),
    inputBox = document.querySelector(".search-input input"),
    suggBox = document.querySelector(".suggBox");
  inputBox.onkeyup = (e) => {
    let userData = e.target.value;
    let A = [];
    if (userData) {
      A = s.filter((d) => {
        return d.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
      });
      A = A.map((d) => {
        return (d = `<li onclick="select(this)">${d}</li>`);
      });
      search.classList.add("active");
      show(A);
    }
  };
  function show(e) {
    suggBox.innerHTML = !e.length
      ? `<li>` + inputBox.value + `</li>`
      : e.join("");
  }
  function select(e) {
    inputBox.value = e.textContent;
  }
});

if i remove $(function(){ ....}) then select(e) working fine

NOTE above code is part of some long jQuery file thats why i need solution in Jquery



Solution 1:[1]

it is because select(e) is inside anonymous function so it can be accessed, you have to create element using document.createElement("li") and attach the listener or simply add click listener to the document and check if target is the element that you wanted.

document.body.onclick = function(e) {
  if (e.target.className == 'item')
    inputBox.value = e.target.textContent
}

demo

$(function() {
  let s = ["aa", "abb", "acc", "adf"],
    search = document.querySelector(".search"),
    inputBox = document.querySelector(".search-input input"),
    suggBox = document.querySelector(".suggBox");
  inputBox.onkeyup = (e) => {
    let userData = e.target.value;
    let A = [];
    if (userData) {
      A = s.filter((d) => {
        return d.toLocaleLowerCase().startsWith(userData.toLocaleLowerCase());
      });
      A = A.map((d) => {
        //  return (d = `<li onclick="select(this)">${d}</li>`); // replace this
        return (d = `<li class="item">${d}</li>`);
      });
      search.classList.add("active");
      show(A);
    }
  };

  function show(e) {
    suggBox.innerHTML = !e.length ?
      `<li>` + inputBox.value + `</li>` :
      e.join("");
  }

  /*function select(e) {
    inputBox.value = e.textContent;
  }*/
  $(document).on('click', '.item', function(){
    inputBox.value = this.textContent;
  })
  
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="search-input">
  <input type="text">
</div>
<div class="search"></div>
<div class="suggBox"></div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1