What is the best way to query across multiple HTML tables?

Is there a way to search across multiple tables in HTML? I currently have code that works for one table, but I need it to work for two or more tables.

This is the code I am using to search for "something" within my table.

<script>
    function myFunction() {
        // Declare variables
        var input, filter, table, tr, td, i;
        input = document.getElementById("myInput");
        filter = input.value.toUpperCase();
        table = document.getElementById("myTable");
        tr = table.getElementsByTagName("tr");
        // Loop through all table rows, and hide those who don't match the search query
        for (i = 0; i < tr.length; i++) {
            if (!tr[i].classList.contains('header')) {
                td = tr[i].getElementsByTagName("td"),
                match = false;
                    for (j = 0; j < td.length; j++) {
                        if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                            match = true;
                            break;
                        }
                    }
                    if(!match){
                        tr[i].style.display = "none";
                    }else{
                        tr[i].style.display = "";
                    }
                }
            }
        }
</script>

This is the structure of the HTML Tables where I want to implement the search functionality.

The issue is that the search functionality only runs on the first table and not on the subsequent ones.

<table class="table" style="text-align: left;" id="myTable">
    <thead>
    <tr>
    </tr>
    </thead>
    <tbody>
        <h4 style="text-align: center;"><strong>FOREIGN MINISTER’S 
        OFFICE</strong></h4>
    <div id="A">
        <tr>
               <td><strong><h5>Designation</strong></h5></td>
               <td><strong><h5>Name</strong></h5></td>
                  <td><strong><h5>Phone</strong></h5></td>
                  <td><strong><h5>Fax</strong></h5></td>
           </tr>
           <tr>
                  <td>Foreign Minister</td>
                  <td>Makhdoom Shah Mahmood Qureshi</td>
                  <td>051-9210335</td>
                  <td>051-9207600</td>
          </tr>
          <tr>
              <td></td>
                 <td></td>
                 <td>051-9203824</td>
                 <td></td>
          </tr>
          <tr>
                <td>Additional Secretary (FMO)</td>
                  <td>Ameer Khurram Rathore</td>
                  <td>051-9210335</td>
                  <td></td>
          </tr>
          <tr>
                  <td>Director (FMO)</td>
                  <td>Syed Mustafa Rabbani</td>
                  <td>051-9207762</td>
                  <td></td>
          </tr>
      <tr>
                  <td>Asstt. Dir (FMO)</td>
                  <td>Muhammad Saad Ahmed</td>
                  <td>051-9207617</td>
                  <td></td>
           </tr>
           <tr>
                  <td>PS to FM</td>
                  <td>Muhammad Bashir Kiyani</td>
                  <td>051-9207762</td>
                  <td></td>
           </tr>    
      </div>
   </tbody>
</table>
<table class="table" style="text-align: left;" id="myTable">
    <thead>
           <tr>
           </tr>
       </thead>
    <tbody>
     <h4 style="text-align: center;"><strong>PARLIAMENTARY SECRETARY’S OFFICE</strong></h4>        
<div id="B">
    <tr>    
           <td><strong><h5>Designation</strong></h5></td>
              <td><strong><h5>Name</strong></h5></td>
              <td><strong><h5>Phone</strong></h5></td>
              <td><strong><h5>Fax</strong></h5></td>
       </tr>
       <tr>
              <td>Foreign Minister</td>
              <td>Makhdoom Shah Mahmood Qureshi</td>
              <td>051-9210335</td>
              <td>051-9207600</td>
       </tr>
       <tr>
              <td></td>
              <td></td>
              <td>051-9203824</td>
              <td></td>
       </tr>
       <tr>
            <td>Additional Secretary (FMO)</td>
              <td>Ameer Khurram Rathore</td>
              <td>051-9210335</td>
              <td></td>
       </tr>
       <tr>
              <td>Director (FMO)</td>
              <td>Syed Mustafa Rabbani</td>
              <td>051-9207762</td>
              <td></td>
       </tr>
       <tr>
              <td>Asstt. Dir (FMO)</td>
              <td>Muhammad Saad Ahmed</td>
              <td>051-9207617</td>
              <td></td>
       </tr>
       <tr>
              <td>PS to FM</td>
              <td>Muhammad Bashir Kiyani</td>
              <td>051-9207762</td>
              <td></td>
       </tr>    
    </div>
</tbody>

How can I enable searching across multiple tables in an HTML environment?

Answer №1

You have assigned the same id to both tables.

The getElementById function will only return one element.

If there are multiple tables, you need to retrieve all tables and iterate over each one.

Please refer to the code snippet below for a solution:

window.onload = function(){
    document.getElementById("myInput").addEventListener("input", myFunction)  
}
function myFunction() {
            // Declare variables
            var input, filter, table, tr, td, i;
            input = document.getElementById("myInput");
            filter = input.value.toUpperCase();
            tables = document.querySelectorAll(".table");

            tables.forEach(function(table) {
                tr = table.getElementsByTagName("tr");
                // Loop through all table rows, and hide those that do not match the search query
                for (i = 0; i < tr.length; i++) {
                    if (!tr[i].classList.contains('header')) {
                        td = tr[i].getElementsByTagName("td"),
                            match = false;
                        for (j = 0; j < td.length; j++) {
                            if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                                match = true;
                                break;
                            }
                        }
                        if (!match) {
                            tr[i].style.display = "none";
                        } else {
                            tr[i].style.display = "";
                        }
                    }
                }
            });

}
<input type="text" id="myInput"/>
        <table class="table" style="text-align: left;" id="myTable1">
                    <thead>
                        <tr>
                        </tr>
                    </thead>
                    <tbody>
                        <h4 style="text-align: center;"><strong>FOREIGN MINISTER’S OFFICE</strong></h4>
                        <div id="A">
                            <tr>

                                <td><strong><h5>Designation</strong></h5></td>
                                <td><strong><h5>Name</strong></h5></td>
                                <td><strong><h5>Phone</strong></h5></td>
                                <td><strong><h5>Fax</strong></h5></td>
                            </tr>
                            <tr>
                                <td>Foreign Minister</td>
                                <td>Makhdoom Shah Mahmood Qureshi</td>
                                <td>051-9210335</td>
                                <td>051-9207600</td>
                            </tr>
                            <tr>
                                <td></td>
                                <td></td>
                                <td>051-9203824</td>
                                <td></td>
                            </tr>
                            <tr>
                                <td>Additional Secretary (FMO)</td>
                                <td>Ameer Khurram Rathore</td>
                                <td>051-9210335</td>
                                <td></td>
                            </tr>
                            <tr>
                                <td>Director (FMO)</td>
                                <td>Syed Mustafa Rabbani</td>
                                <td>051-9207762</td>
                                <td></td>
                            </tr>
                            <tr>
                                <td>Asstt. Dir (FMO)</td>
                                <td>Muhammad Saad Ahmed</td>
                                <td>051-9207617</td>
                                <td></td>
                            </tr>
                            <tr>
                                <td>PS to FM</td>
                                <td>Muhammad Bashir Kiyani</td>
                                <td>051-9207762</td>
                                <td></td>
                            </tr>    
                        </div>
                    </tbody>
                    </table>

        <table class="table" style="text-align: left;" id="myTable2">
                            <thead>
                                <tr>
                                </tr>
                            </thead>
                            <tbody>
                        <h4 style="text-align: center;"><strong>PARLIAMENTRY SECRETARY’S OFFICE</strong></h4>        
                        <div id="B">
                                <tr>    
                                    <td><strong><h5>Designation</strong></h5></td>
                                    <td><strong><h5>Name</strong></h5></td>
                                    <td><strong><h5>Phone</strong></h5></td>
                                    <td><strong><h5>Fax</strong></h5></td>
                                </tr>
                                <tr>
                                        <td>Foreign Minister</td>
                                        <td>Makhdoom Shah Mahmood Qureshi</td>
                                        <td>051-9210335</td>
                                        <td>051-9207600</td>
                                    </tr>
                                    <tr>
                                        <td></td>
                                        <td></td>
                                        <td>051-9203824</td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>Additional Secretary (FMO)</td>
                                        <td>Ameer Khurram Rathore</td>
                                        <td>051-9210335</td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>Director (FMO)</td>
                                        <td>Syed Mustafa Rabbani</td>
                                        <td>051-9207762</td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>Asstt. Dir (FMO)</td>
                                        <td>Muhammad Saad Ahmed</td>
                                        <td>051-9207617</td>
                                        <td></td>
                                    </tr>
                                    <tr>
                                        <td>PS to FM</td>
                                        <td>Muhammad Bashir Kiyani</td>
                                        <td>051-9207762</td>
                                        <td></td>
                                    </tr>    
                        </div>
                    </tbody>
    </table>

Answer №2

Utilizing document.getElementById("myInput") will limit your search to just one specific element.

Consider searching for a class instead, which could potentially return multiple elements.

Try using ".myTableClass" to target elements with that particular class name.

Answer №3

  1. Make sure to use unique IDs for each table, avoid using the id 'myTable' for both tables
  2. To apply your filter function, target both tables by their class 'table' and iterate through them:

function filter() {
    // Initialize variables
    var input, filter, tables, tr, td, i;
    input = document.getElementById("myInput");
    filter = input.value.toUpperCase();
    tables = document.getElementsByClassName("table");
    
    for(var k = 0; k < tables.length; k++) {
        tr = tables[k].getElementsByTagName("tr");
        // Iterate over all table rows, hide those that don't match the search query
        for (i = 0; i < tr.length; i++) {
            if (!tr[i].classList.contains('header')) {
                td = tr[i].getElementsByTagName("td"),
                    match = false;
                for (j = 0; j < td.length; j++) {
                    if (td[j].innerHTML.toUpperCase().indexOf(filter) > -1) {
                        match = true;
                        break;
                    }
                }
                if (!match) {
                    tr[i].style.display = "none";
                } else {
                    tr[i].style.display = "";
                }
            }
        }
    }
}
<form>
  <label for="myInput">Search:</label>
  <input id="myInput" type="text" onKeyup="filter()">
</form>

<h4 style="text-align: center;"><strong>FOREIGN MINISTER’S OFFICE</strong></h4>
<table class="table" style="text-align: left;">
  <thead>
    <tr>
      <th>Designation</th>
      <th>Name</th>
      <th>Phone</th>
      <th>Fax</th>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td>Foreign Minister</td>
        <td>Makhdoom Shah Mahmood Qureshi</td>
        <td>051-9210335</td>
        <td>051-9207600</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td>051-9203824</td>
        <td></td>
    </tr>
    <tr>
        <td>Additional Secretary (FMO)</td>
        <td>Ameer Khurram Rathore</td>
        <td>051-9210335</td>
        <td></td>
    </tr>
    <tr>
        <td>Director (FMO)</td>
        <td>Syed Mustafa Rabbani</td>
        <td>051-9207762</td>
        <td></td>
    </tr>
    <tr>
        <td>Asstt. Dir (FMO)</td>
        <td>Muhammad Saad Ahmed</td>
        <td>051-9207617</td>
        <td></td>
    </tr>
    <tr>
        <td>PS to FM</td>
        <td>Muhammad Bashir Kiyani</td>
        <td>051-9207762</td>
        <td></td>
    </tr>
  </tbody>
</table>

<h4 style="text-align: center;"><strong>PARLIAMENTRY SECRETARY’S OFFICE</strong></h4>

<table class="table" style="text-align: left;">
  <thead>
    <tr>
      <th>Designation</th>
      <th>Name</th>
      <th>Phone</th>
      <th>Fax</th>
    </tr>
  </thead>
  <tbody>
    <tr>
        <td>Foreign Minister</td>
        <td>Makhdoom Shah Mahmood Qureshi</td>
        <td>051-9210335</td>
        <td>051-9207600</td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td>051-9203824</td>
        <td></td>
    </tr>
    <tr>
        <td>Additional Secretary (FMO)</td>
        <td>Ameer Khurram Rathore</td>
        <td>051-9210335</td>
        <td></td>
    </tr>
    <tr>
        <td>Director (FMO)</td>
        <td>Syed Mustafa Rabbani</td>
        <td>051-9207762</td>
        <td></td>
    </tr>
    <tr>
        <td>Asstt. Dir (FMO)</td>
        <td>Muhammad Saad Ahmed</td>
        <td>051-9207617</td>
        <td></td>
    </tr>
    <tr>
        <td>PS to FM</td>
        <td>Muhammad Bashir Kiyani</td>
        <td>051-9207762</td>
        <td></td>
    </tr> 
  </tbody>
</table>

Answer №4

If you want to select multiple elements in the DOM, you can try using querySelectorAll which will return a NodeList of all matching elements. For example, to select all table rows within tables with the class "table", you can use document.querySelectorAll("table.table tr").

var rows = document.querySelectorAll("table.table tr");
for(var i in rows){
var tr = rows[i];
if (!tr.classList.contains('header')) {
td = tr.getElementsByTagName("td"),
match = false;
for (j = 0; j < td.length; j++) {
if (td[j].innerHTML.toUpperCase().indexOf(filter.toUpperCase()) > -1) {
match = true;
break;
}
}
if (!match) {
tr.style.display = "none";
} else {
tr.style.display = "";
}
}
}

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

Creating distinct short identifiers across various servers

Utilizing the shortid package for creating unique room IDs has proven effective when used on a single server. However, concerns arise regarding the uniqueness of IDs generated when utilized across multiple servers. Is there a method to ensure unique ID g ...

Unusual occurrence in Chrome when checking definitions: ReferenceError: x is not defined

Recently, I've come across some odd behavior in Chrome following its latest update. Whenever I try to determine if a variable is defined, it ends up triggering an uncaught error like the one shown below: if(x) { alert('x is defined.'); } T ...

Choosing the vue js el by utilizing the CSS attribute selector: A step-by-step guide

Here is my situation: <div data-identifier='app'> ... </div> This is the Vue js code I am working with: var app = new Vue({ el: '[data-identifier]', data: { }, ...

Tips for showcasing my database in real-time using Php, JavaScript, jQuery and AJAX

Is there a way to display my MySQL database in real-time through AJAX without overloading it with excessive queries? I am currently utilizing jQuery's load function, but I suspect there may be a more efficient method. Can you offer any advice or alter ...

Eliminate Bootstrap's validation glyphs

Issue Description I am attempting to eliminate the validation icons from Bootstrap, such as the "x" and "check" symbols. Despite my efforts to search thoroughly, I have been unable to locate where these icons are located in the code. Code Sample You can ...

Using PHP with the CodeIgniter framework, learn how to use Javascript to delete specific values in an HTML table row

Within my CodeIgniter project, I have a table that is being dynamically generated by Ajax. Each row in the table has a button to delete the corresponding entry from both the HTML table and the MySQL table. I have already found a way to remove the HTML tab ...

How can I use React Router to maintain the selected list item in the side drawer's state?

Seeking help with react-router and material UI integration. I have successfully integrated routes with my material UI drawer list items, along with custom styling to highlight the selected item upon clicking. However, I am encountering an issue where the s ...

What is the best way to change the value of a key in a JSON Object?

I am currently utilizing _underscore library. My goal is to change the value of a specific key. var users = [{ "_id": { "$oid":"3426" }, "name":"peeter" }, { "_id": { "$oid":"5a027" }, "name":"ken" }, { "_id": { "$oid":"5999" }, ...

Finding the position or coordinates of a div element in Blazor

I am currently working on a popup component that needs to be movable. The default position is set to top:0;left:0;, causing the popup to appear in the top-left corner of the page. However, I want it to be centered on the page and then retrieve the Top Left ...

Is it possible in JavaScript to create a custom function that inherits from the Number object?

Yes, I have figured out a way to accomplish this... We can create a custom function that operates on numbers without modifying the Number prototype directly. For example: var squareNumber = function(num) { return num * num; } squareNumber(4); // Output: ...

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

Interactive Timekeeping Tool with AngularJS Alarm Feature

I have successfully implemented the functionality to display the system time and date. Additionally, I have set up textboxes for users to input the time they want to set as their first alarm. My current goal is to trigger a particular action once the syst ...

Checkbox click event not triggering properly

I am facing challenges in triggering an onclick event for the "Elevation" checkboxes located at the URL provided above. <input type="checkbox" value="A" id="elevation_A" onclick="changeElevation(this.value);" /> For some reason, the "changeElevati ...

Tips for displaying two input decorations in Material UI beside one another within a text field

In the Text Field demonstration, I noticed input adornments at the start and end. However, I am looking to have two input adornments at the end specifically. I attempted to add them using endAdornment: {InputAdornment InputAdornment}, but encountered an er ...

Tips for implementing owl carousel in Nuxt.REACT_UNITS_CODIFY

Is there a way to make the script function on every page without the need for these pages to be reloaded? I have the Owl Carousel script in my static folder, and I have already included it in nuxt.config.js as shown below: head: { title: 'title&ap ...

Error in AJAX POST: base64 string formatting issue

Struggling with making an AJAX POST successfully upload and retrieve a base64 string to/from my SQL database. Upon receiving the string from the database via AJAX, it appears to be the same base64 string, but with random line breaks that render it non-func ...

Utilizing AJAX and PHP to dynamically update MYSQL database via a dropdown selection

I am currently facing an issue with running SQL queries through AJAX after the selection in a dropdown box changes. I would appreciate any assistance that can be offered. Context My task involves creating a daily calendar for a gym to display all the clas ...

Approximately 20% of spoken words are not accurately conveyed by Speech Synthesis Google Voices, failing to adhere to the intended voice selection

When using speechSynthesis.speak(utterance) in Chrome with the "Google UK English Female" voice, there is an issue where a male voice is randomly spoken instead. Any thoughts on how to resolve this? Latest Update: July 26th, 2022 This appears to be a bug ...

Adjust the width of the table by utilizing the border-collapse property set to collapse

I am completely baffled by this situation. Whenever I adjust the border-width of a table (either dynamically with JavaScript or in Chrome Dev Tools) where border-collapse: collapse; is set, transitioning from a border width of 1px (#1) to a larger value (# ...

Exploring the capabilities of nested WebGL render targets in the three.js library

I am currently developing an application for the Oculus Rift using JavaScript, three.js, and OculusRiftEffect.js. In order to create a transparent portion of a 2D ring for the menu, I am attempting to generate a MeshBasicMaterial.alphaMap texture on a Web ...