简体   繁体   中英

I am trying to create a search bar using javascript in VISUAL STUDIO but I have not yet succeeded

html File: I have used some divs and inside i have introduced some titles and images.

In the search bar i just want that when i enter a title the full div appears on the screen when i search.

<body>
    <div class="input">
        <input type="text" placeholder="Search.." id="searchbar" onkeyup="search_bar()">
        <button type="submit"><i class="fa fa-search"></i></button>
    </div>
    <div class="s10plus" id="divs">
        <h2>Samsung Galaxy S10 Plus</h2>
        <img src="Images/s10plus.png"></img>
        <p id="precios10">Price : $600</p>
    </div>
    <div class="samsunga10">
        <h2>Samsung Galaxy A10</h2>
        <img src="Images/a10.png"></img>
        <p id="precioa">Price:$600</p>
    </div>
    <div class="samsunga20">
        <h2>Samsung Galaxy A20</h2>
        <img src="Images/a20.png"></img>
        <p id="precio">Price:$600</p>
    </div>
</body>
  

file.js

function search_bar() {
    var a;
    var search = document.getElementById('searchbar');
    var filter = search.input.toLowerCase();
    var ul = document.getElementsByClassName('s10plus');
    var nodes = ul.getElementsByTagName('h2').length;

    for (i = 0; i < nodes; i++) {
        a = nodes[i].getElementsByTagName('h2')[0];
        if (a.innerHTML.toLowerCase().indexOf(filter) > -1) {
            nodes[i].style.display = "";
        } else {
            nodes[i].style.display = "none";
        }
    }
}

Could you share a Codepen or Codesandbox or add a snipped here in SO?

in your Js code: "li" is not defined which makes it hard to understand your code exactly. Also, setting display: "", is not a valid css property. I recommend setting it to display: "inherit".

The class "s10plus" at:

          var ul = document.getElementsByClassName('s10plus');

will always get 1 element since in your html only one div has that class.

Try to adjust these issues and see if you can get any further

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM