What is the best way to enable my search function to filter out specific items from a table?

Currently, I have created a table populated with data fetched from a JSON file. Now, my focus is on implementing a search functionality that filters out items based on user input and displays only those table rows matching the search criteria. The code snippet for the function I am currently using is as follows:

// Search function
function searchTable() {
    var input, filter, found, table, tr, td, i, j;
    input = document.getElementsByClassName("searchBar");
    filter = input.value.toUpperCase();
    table = document.getElementById("productTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        for (j = 0; j < td.length; j++) {
            if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                found = true;
            }
        }
        if (found) {
            tr[i].style.display = "";
            found = false;
        } else {
            tr[i].style.display = "none";
        }
    }
}

Below is the HTML structure of the table where I intend to implement the search filter:

<input class="form-control searchBar" type="text" name="search" placeholder="search">
<table class="table table-hover">
    <thead>
        <tr>
            <th scope="col">#</th>
            <th scope="col">Product Name</th>
            <th scope="col">Free Stock</th>
            <th scope="col">Price</th>
            <th scope="col">Actions</th>
        </tr>
    </thead>
    <tbody id="productTable">
        <tr>
        </tr>
    </tbody>
</table>

Answer №1

If you're looking for a simple and efficient way to search within an HTML table using pure JavaScript, look no further. Here's a compact solution that covers every cell in the table:

<body style="background:blue;">
<input id='searchInput' onkeyup='performSearch()' type='text'>
<table id='dataTable'>
  <thead>
    <tr>
      <th scope="col">#</th>
      <th scope="col">Product Name</th>
      <th scope="col">Availability</th>
      <th scope="col">Price</th>
      <th scope="col">Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>1</td>
      <td>Blue</td>
      <td>Lorem</td>
      <td>Ipsum</td>
      <td>button</td>
    </tr>
    <tr>
      <td>2</td>
      <td>Red</td>
      <td>elit</td>
      <td>Mumbai</td>
      <td>button</td>
    </tr>
    <tr>
      <td>3</td>
      <td>Green</td>
      <td>sud</td>
      <td>Dummy</td>
      <td>button</td>
    </tr>
  </tbody>
</table>
<script>
function performSearch() {
    var input, filter, found, table, tr, td, i, j;
    input = document.getElementById("searchInput");
    filter = input.value.toUpperCase();
    table = document.getElementById("dataTable");
    tr = table.getElementsByTagName("tr");
    for (i = 0; i < tr.length; i++) {
        td = tr[i].getElementsByTagName("td");
        for (j = 0; j < td.length; j++) {
            if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                found = true;
            }
        }
        if (found) {
            tr[i].style.display = "";
            found = false;
        } else {
            tr[i].style.display = "none";
        }
    }
}
</script>
</body>

Answer №2

One issue is that getElementsByClassName does not directly return an element; it returns a NodeList. If you have only one element with the class of "searchBar," you would reference it like this:

input = document.getElementsByClassName("searchBar")[0];

Here is the updated script incorporating your existing ID:

function searchTable() {
        var input, filter, found, table, tr, td, i, j;
        input = document.getElementsByClassName("searchBar")[0];
        filter = input.value.toUpperCase();
        table = document.getElementById("productTable");
        tr = table.getElementsByTagName("tr");
        for (i = 0; i < tr.length; i++) {
            td = tr[i].getElementsByTagName("td");
            for (j = 0; j < td.length; j++) {
                if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                    found = true;
                }
            }
            if (found) {
                tr[i].style.display = "";
                found = false;
            } else {
                tr[i].style.display = "none";
            }
        }
    }

However, if you are sure there will be only one such element, consider assigning it an id and using getElementById instead to get direct access to the element.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible to activate a block display for an article based on the class value when a radio

Here is the HTML code snippet I'm working with: <div id="contentapp"> <input type="radio" name="menu" id="interest" checked> <input type="radio" name="menu" id="about"> <div id="tab"> <label for="intere ...

Retrieving attribute of a span element inside a nested div

Newbie to web scraping and facing an issue. I am trying to extract the value of data-value from the span with class "DFlfde SwHCTb". However, I keep getting an undefined return. Can someone point out what error I made in the code below? const axios = requi ...

Leveraging the Railway Pathway from the Google Maps API

I need to customize my map to display only railway stations instead of the entire map. How can I achieve this? Below is the code I have attempted: <html> <head> <style type="text/css"> html { height: 100% } ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

The issue with CSS z-index not functioning properly when using absolute positioning

Here is the issue I'm facing: I have multiple div containers in my code. .outer { position: relative; z-index: 1; } .inner { position: absolute; z-index: 999; } <div class="outer"> <div class="inner"> <div class="option ...

Deleting data using the Ajax method in a Spring Boot application

Despite my efforts to find a solution by researching various forums discussing the same issue, I am still unable to resolve the error message 'Request method 'DELETE' not supported'. An Ajax call is triggered when a user on the client- ...

Non-clickable image

My social media page icons are not hyperlinked, and I can't figure out why. I've surrounded them with the href attribute, but for some reason, it's not working. Can anyone provide assistance? Here is the HTML code: <!DOCTYPE html> ...

What is the key to ensuring the content in your canvas adapts to different screen sizes

Greetings! I wanted to extract the values from this specific meta tag: <meta name="viewport" property="viewport" content="width-device-width, initial-scale=1"> To retrieve content from a meta tag using JavaScript, I used the following code snippet: ...

How to add an 'alt' text tag to a background image sprite

I have a button that opens a new browser window, so I've added alternate_text and title tags to notify the user that a NEW window will open when hovered over. <img class="mp3PlayBtn" alt="Mp3 player opens in popup window" title="Mp3 player opens i ...

Disregard the popstate triggered by Safari's Initial Page Load

Utilizing pushState, I am able to generate the page view on popstate events based on the history.state of the current page. In cases where there is no history.state present, my intention is to reload the document (hopefully). window.onpopstate = function ...

I am unable to produce sound by clicking on the drum machine

My goal is to develop a basic react drum machine project that I discovered on freecodecamp. The objective is to display 9 drumpads and trigger sound upon clicking. Update: I have successfully rendered all the keys but I am facing issues with the function ...

Implementing child components in React using TypeScript and passing them as props

Is it possible to append content to a parent component in React by passing it through props? For example: function MyComponent(props: IMyProps) { return ( {<props.parent>}{myStuff}{</props.parent>} } Would it be feasible to use the new compone ...

What are the best ways to customize exported and slotted components in Svelte?

Is there a similarity between Svelte slots and vanilla-js/dom functionality (I'm having trouble with it). In html/js, I can achieve the following: <style> body {color: red;} /* style exposed part from outside */ my-element::par ...

How to properly align an object in a specified ul, li list

I'm currently facing an issue while building a Joomla site. I have set a background image for my li elements, but the items within the li are not centered as expected. The website I am working on is www.outlawsofhealth.com. The specific list in quest ...

Is it not possible to change node labels in D3.js after clicking on a node?

After being inspired by this link, I successfully created a basic network visualization app using D3.js. The app reads node names from a textarea on an HTML page and then constructs a network where all nodes are interconnected. All the relevant code can ...

Automatically hide a label after a certain amount of time following a button click

Currently, I am working with ASP.NET and C#. Within my application, there is a registration form that includes a label to display the status of registration, either success or failure. The content of this label is determined dynamically in the codebehind ...

Using the useState hook will help avoid any crashes when running on IE11

I recently added a new repository to my GitHub account. The file dist/index.htm is causing Internet Explorer 11 to crash, displaying the error message: "unable to get property 'root' of undefined or null reference." This issue arises when I u ...

What is the best way to display an image path and add it to the Ajax success function in a CodeIgniter application?

I am struggling to display my image path correctly using append and a variable to store the value. However, whenever I try, it results in an error. Let me provide you with the code snippet: <script type="text/javascript"> $(document).ready(funct ...

The AJAX calendar control remains unchanged after a reset

I am currently facing an issue with my ajax calendar control used in a form for selecting dates. The problem arises when I select a date from the previous year and then click on the reset button. Even though the text box is cleared, the calendar control s ...

Using `overflow: hidden` on a table will result in the bottom and right borders disappearing

I am facing an issue where the border of my table is being cut off when using overflow: hidden. Below is an example code snippet illustrating this problem. <style> table { border-collapse: collapse; } table { ...