GP45
GP45

Reputation: 29

Search input not found by JavaScript

Hello this is my first time asking a question on here so please forgive any format mistakes I make.
I am trying to make a realtime search on a web page that uses HTML,JavaScript,CSS,and PHP. The problem I am running into is that my JavaScript can not seem to find my search input ID so I get this error when I load the web page:

   Uncaught TypeError: Cannot read property 'addEventListener' of null at search.js:3

Here is a snippet of the js and html:

var search_bar = document.getElementById("_input");
console.log(search_bar);
search_bar.addEventListener('input', package_search);
var _package = document.getElementsByClassName('panel-title');
var package_array = [];

while (_package.lenth > 0) {
  var P_names = _package[0].querySelector("package_name").textContent;
  var package_obj = {
    name: P_names
  };
  package_array.push(packagae_obj);
  console.log(package_obj);
  P_names[0].remove();
}

function package_search() {
  var input = search_bar.value;
  var filter = input.toUpperCase();
  var package_name = document.getElementsByClassName("panel-heading");
  var _name = document.getElementsByClassName("panel-title");
  var a, txtValue, i;
  console.log(_name);
  for (i = 0; i < _name.length; i++) {
    txtValue = _name[0].textContent || _name[0].innertext;
    if (txtValue.toUpperCase().includes(filter)) {
      package_name[i].style.display = "";
    } else {
      package_name[i].style.display = "none";
    }
  }
}
<div class="container">
  <div class="row">
    <div class="col-xs-6">
      <h3>Packages</h3>
      <div class="search_bar" id="search_bar">
        <ul class="search_" id="search_" style="margin-left: 66%; margin-top: -5%;">
          <li class="search_box">
            <input type="text" id="_input" placeholder="Search...">
            <button type="button" id="search_button" style="height: 23px; 
   width:63px;">Search</button>
          </li>
        </ul>
      </div>
      <div class="panel-group" id="accordion">

Any suggestions on a solution to this problem will be greatly appreciated thank you.

Upvotes: 1

Views: 265

Answers (1)

Omar Siddiqui
Omar Siddiqui

Reputation: 1655

Your JS is probably firing too quickly. In the snippet, there is no such issue with picking up the element. Wrap your JS code inside a DOMContentLoaded eventListener. It will make sure that your JS is executed only after all elements have been loaded into the DOM.

document.addEventListener('DOMContentLoaded', () => {
   //All your JS code here
})

Upvotes: 1

Related Questions