What is the best way to design a filter search function to simultaneously search through information from two separate columns within a table

Currently, the search function is only searching within the first column of a table. The code for this search function was adapted from w3schools. Here is the JavaScript code snippet:

function myFunction() {
  // 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 rows to filter based on user input
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }
  }
}

Answer №1

Give this a shot

executeSearch() {
  // Setting up variables 
  var input, filter, table, tr, td, i;
  input = document.getElementById("searchInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("dataTable");
  tr = table.getElementsByTagName("tr");

  // Iterating through each table row to show or hide based on search query
  for (i = 0; i < tr.length; i++) {
    //First column
    col_1 = tr[i].getElementsByTagName("td")[0];
    //Second column
    col_2 = tr[i].getElementsByTagName("td")[1];
    if (col_1 || col_2) {
      if (col_1.innerHTML.toUpperCase().indexOf(filter) > -1 || col_2.innerHTML.toUpperCase().indexOf(filter)> -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    } 
  }
}

Check out the demo

Answer №2

To incorporate multiple columns in your loop, you will need to expand it as shown below:

//Count the number of columns
var columnCount = table.getElementsByTagName("tr")[0].childNodes.length;

for (i = 0; i < tr.length; i++) {

    for (j = 0; j < columnCount; j++) {

        td = tr[i].getElementsByTagName("td")[j];

        if (td) {

                var tempText;

                if(td.childNodes[1].getAttribute('id')){

                    tempText = td.childNodes[1].getAttribute('id');

                }                   
                else {

                    tempText = td.innerHTML.toUpperCase();

                }

                try {
                    if (tempText.indexOf(filter) > -1) {
                        tr[i].style.display = "";
                    } else {
                        tr[i].style.display = "none";
                    }
                }
                catch(err) {}

        }

    }

}

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

Turn off images using Selenium Python

In order to speed up the process, I believe that disabling images, CSS, and JavaScript can help since Webdriver waits for the entire page to load before moving on. from selenium import webdriver from selenium.webdriver.firefox.firefox_profile import Firef ...

Why does it display 'Undefined' when I attempt to access an object in an array in Next.js?

I am currently working on a way to display sub Products related to the main product. I have attempted to extract the product code from the URL and then retrieve sub-products that correspond to the main product code. List of Products and Sub products const ...

software tool for managing state transitions

Can anyone recommend a superior javascript library for workflows? Right now, I'm utilizing Joint JS, but I require something with a more visually appealing interface (users tend to prefer that). ...

Viewing Image in Modal on Click

Despite numerous attempts, I have been unable to make this work, even after trying various examples. The issue at hand is with a list of imageURL's that are displayed on the webpage. The goal is to allow users to click on an image, which would then o ...

JQuery does not have the ability to compare the current date and

I've encountered an issue while comparing two date scripts that resulted in incorrect output. Here is the code that I used: var current = new Date(); var date = new Date($(this).val()); alert(current) == "Sat Aug 23 2014 14:42:00 GMT+0700 (ICT)" aler ...

Conquering Challenges Across Multiple Disciplines

Is there a solution to solving the cross domain issues that arise when trying to fetch data from a different web server on the client-side, in violation of the Same Origin policy? ...

"Trouble arose when I tried to incorporate additional functions into my JavaScript code; my prompt feature is not

As a beginner in HTML and JS coding, I am working on creating a page that prompts user input for a name and then executes animations using radio buttons. However, after adding functions for radio button changes, my prompt is no longer functioning properly. ...

Adjust the size of iCheck jQuery radio buttons

I have implemented the iCheck Plugin for radio buttons in Angular Directive, but I am facing an issue with resizing the radio button to a smaller size. Does anyone have any suggestions or solutions for this? ...

Tips for recognizing components within the #document are as follows:

I am currently utilizing xpath to extract data from a dynamic table in an HTML document. The specific information I am looking for is contained within a tag identified as #document. However, I am encountering difficulties including this unique element in ...

Is it correct that when values are saved without being paired with keys, they are stored as keys within a JavaScript object?

Consider a scenario where you have an object: const obj = { time, difficulty, distance, } Are the values inside the object saved as keys? If I were to use Object.keys() on the object, would I get an array of individual string elements? ...

Node.js body-parser is returning a value of 'undefined'

It's quite frustrating how something that seems simple on video tutorials is giving me a hard time. I followed the instructions to set up a node app using express with a dummy HTML (via EJS). My goal is to capture the data entered by a user in an inpu ...

In Chrome, it seems like every alternate ajax request is dragging on for ten times longer than usual

I've been running into an issue with sending multiple http requests using JavaScript. In Chrome, the first request consistently takes around 30ms while the second request jumps up to 300ms. From then on, subsequent requests alternate between these two ...

What methods are available for utilizing DOMStringMap within TypeScript?

Imagine I have this function: angular.forEach(myElements, function prepareElements(myEl: HTMLElement, index) { myEl.dataset.myProperty = "whatever"; }) However, I encounter an issue with error TS2094: The property 'myProperty' does not exi ...

Displaying the API request using the UseEffect API is not working upon the page

Sorry if this question has been asked before, but I’m really stuck on this small bug. I’m trying to display a collection of tweets from Firestore when the page loads, but currently it only works after a post request. Here’s my code: useEffect(() ...

Angular 2 Element Selection: Dealing with Unrendered Elements

This form consists of three input fields: <div> <input *ngIf = "showInputs" #input1 (change)="onTfChnage(input2)" type="text"/> <input *ngIf = "showInputs" #input2 (change)="onTfChnage(input3)" type="text"/> <input *ngIf = "showInp ...

What is causing the issue with the "Inline-block" property in this CSS code?

Please review the CSS code provided below for styling instructions. /*rex is the container of ex,ex2,ex3*/ div.rex{ height:200px; border:0px; margin:60px auto; padding: 0; vertical-align:top; } div.ex{ width:34%; height:200px; background-color:#4f443a; ...

Loading the static content page in Ionic can be slower the first time on a mobile device

My static page contains over 300 lines of text within the HTML file. <ion-content> <p text-warp> //my text with </p> </ion-content> When I view this page in my browser, it loads immediately. However, ...

Retrieve the currently logged-in user whenever the component is rendered using React's Context API

For my small React project, I am utilizing ContextAPI. Whenever I hit the /login endpoint, I store the user's token using an HttpOnly Cookie. Below is the code for UserContext.js, which encapsulates all components (children) within App.js import axio ...

Validating if a specific criterion is met by any Document in Mongoose Library using JavaScript

I'm currently exploring a method to run through documents and utilize the .find method to verify if there is a Document that satisfies certain conditions. Here's an example: //example model const example = new ExampleModel ({ exampleName : &qu ...

Background image specifically for the Fullcalendar sun component

When setting a background image for Sunday in the month view, I noticed that the day "Sunday" in the header is also getting the same background. The CSS for the table thread has classes like .fc-sun and .fc-mon set as well, but I'm not sure how to rem ...