Home > Back-end >  Setting up a search function on a webpage
Setting up a search function on a webpage

Time:05-18

Right, so I've managed to cobble together something that sort of works in terms of a search function within my webpage, however say I search for "Amethyst" it'll group "Placeholder1" into the search as well.

There's probably something very obvious that I'm missing here, but I'll put a small snippet of the code here, not enough to re-create but it's fairly straight forward.

var input = document.getElementById("myInput");
input.addEventListener("input", myFunction);

function myFunction(e) {
  var filter = e.target.value.toUpperCase();

  var list = document.getElementById("products");
  var divs = list.getElementsByTagName("div");
  for (var i = 0; i < divs.length; i  ) {
    var a = divs[i].getElementsByTagName("a")[0];

    if (a) {
      if (a.innerHTML.toUpperCase().indexOf(filter) > -1) {
        divs[i].style.display = "";
      } else {
        divs[i].style.display = "none";
      }
    }
  }

}
<input type="text" id="myInput" placeholder="Search" onkeyup="myFunction()" style="font-size:20px; padding-left: 15px;">



<div id="products"  style="width:100%">
      
 <div >
       <a href="#"><div >
        <div >
          <img src="C:\Users\Harrison Gobey\Downloads\Dice\amethyst1.png" style="width:100%">
          <div >
          </div>
        </div>
        <p>Amethyst<br>£45.00</p>
      </div></a>
     
      <a href="#"><div >
        <div >
          <img src="C:\Users\Harrison Gobey\Downloads\Dice\bloodstone1.png" style="width:100%">
          <div >
            <button >Buy now <i ></i></button>
          </div>
        </div>
        <p>Placeholder1<br>£0.00</p>
      </div></a>
</div> 

NOTE: This is not enough code to replicate anything, but I'm fairly certain the problem lies within this code.

If there's anything else you'd need to help that I've omitted then please let me know. Thanks!

CodePudding user response:

The main issue here is that you're attempting to get the value of e.target.value.toUpperCase(), which is undefined. What you actually want is the uppercased value of myInput, since that's what you'll want to find in your HTML content.

Here's a refactor of your script using querySelector with your existing HTML content that will work (and a more efficient for loop). This code will only look at the paragraph tag that contains your description.

<script>
var input = document.getElementById("myInput");
input.addEventListener("input", myFunction);

function myFunction() {

  var filter = document.getElementById("myInput").value.toUpperCase();
  
  var paragraphs = document.querySelectorAll("#products div a p")
  
  for (let i=0, p; p = paragraphs[i]; i  )
  {
     if (p.innerHTML.toUpperCase().indexOf(filter) > -1)
     {
        p.parentElement.parentElement.style.display = "block";
    }
    else
    {
        p.parentElement.parentElement.style.display = "none";
    }
  }
}
</script>
  • Related