Search code examples
javascripthtmlonclickuncaught-reference-error

Uncaught ReferenceError: selectInput is not defined at HTMLLIElement.onclick


I have this function that is responsible for showing all possible title that are inside my database, and I keep having problem with my function selectInput.

The selectInput function is responsible for putting the list that was clicked by the user inside the inputBox.

function displayAllTitles(availableKeywords, availableKeyTitle) {

  const resultsBox = document.querySelector(".result-box");
  const inputBox = document.getElementById("input-box");

  inputBox.onkeyup = function() {
    let result = [];
    let input = inputBox.value;

    if (input.length) {
      result = availableKeywords.filter((keyword) => {
        return keyword.toLowerCase().includes(input.toLowerCase());
      });
      console.log(result);
    }
    display(result);
  }

  function display(result) {
    const content = result.map((list) => {
      return "<li onclick=selectInput(this)>" + list + "</li>";
    });
    resultsBox.innerHTML = "<ul>" + content.join('') + "</ul>";
  }

  function selectInput(list) {
    inputBox.value = list.innerHTML;
    resultsBox.innerHTML = '';
  }
}

and I keep getting the error Uncaught ReferenceError: selectInput is not defined at HTMLLIElement.onclick, how do I fix this?

Here is my html file:

<div class="search-box">
  <div class="row">
    <input
     type="text"
     placeholder="Search"
     id="input-box"
     autocomplete="off"
    />
    <div class="result-box" id="result-box">
    </div>
  </div>
</div>

Solution

  • The selectInput function is only visible to displayAllTitles function. So we cannot access it from the DOM. I think you can attach the function reference like below and append it to the DOM.

    function display(result) {
    
        const ul = document.createElement('ul');
    
        for (let i = 0; i < result.length; i++) {
            const li = document.createElement('li');
            li.textContent = result[i];
            li.onclick = () => selectInput(result[i]);
            ul.appendChild(li);
        }
    
        resultsBox.innerHTML = '';
        resultsBox.appendChild(ul);
    }
    function selectInput(list) {
        inputBox.value = list;
        resultsBox.innerHTML = '';
    }