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

Viewed 37

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

1 Answers

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>

Related