Fine-tuning Table Filter Javascript

I need help modifying some JavaScript code that currently searches for user input in the first column of a table and hides rows that do not contain that text. I want to update it so that it searches both columns 1 and 2:

HTML:

<input type="text" id="myInput" onkeyup="myFunction()" placeholder="Search for names.." title="Type in a name">
<table id="myTable">
  <tr class="header">
    <th style="width:60%;">Name</th>
    <th style="width:20%;">Country</th>
    <th style="width:20%;">Size</th>
  </tr>
  <tr>
    <td>Joe Smith</td>
    <td>Canada</td>
    <td>Medium</td>
  </tr>
    <tr>
    <td>Jane Doe</td>
    <td>Germany</td>
    <td>Small</td>
  </tr>
</table>

In the example above, you can enter either "Jane" or "Germany" to filter and display the corresponding row.

JAVASCRIPT:

<script>
function myFunction() {
  var input, filter, table, tr, td, i, txtValue;
  input = document.getElementById("myInput");
  filter = input.value.toUpperCase();
  table = document.getElementById("myTable");
  tr = table.getElementsByTagName("tr");
  for (i = 0; i < tr.length; i++) {
    td = tr[i].getElementsByTagName("td")[0];
    if (td) {
      txtValue = td.textContent || td.innerText;
      if (txtValue.toUpperCase().indexOf(filter) > -1) {
        tr[i].style.display = "";
      } else {
        tr[i].style.display = "none";
      }
    }       
  }

}
</script>

Answer №1

Give this a try:

for (i = 0; i < tr.length; i++) {
   var found = false;
   for (j = 0; j < 3; j++){
      td = tr[i].getElementsByTagName("td")[j];
      if (td) {
          txtValue = td.textContent || td.innerText;
          if (txtValue.toUpperCase().indexOf(filter) > -1) {
              found = true;
              break;
          }
       }
    }
    if (found) {
        tr[i].style.display = "";
    } else {
        tr[i].style.display = "none";
    }
  }

Iterate through each column of the table rows, breaking the loop when text is found. After completing the loop, check if text was found and adjust the display accordingly.

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

Having difficulty kicking off a fresh React project on Windows

I've encountered an issue while setting up my React application on Windows OS. After running npm start, the application fails to load on localhost:3000, showing the error message Cannot GET /. Below is the project structure: - webpack.config.js - p ...

Error: The property 'ss' cannot be accessed because it is undefined

Our main source page will be index.html, while Employees.html is where our results end up. An error occurred: TypeError - Cannot read property 'ss' of undefined Error in the code: let rating = req.body.ss; Seeking assistance please >< C ...

Creating default values for MongoDB databases using bdhash in Express.js and mongoose asynchronously

What is the best way to set a default value (like bdhash which is async) for a field in my mongoose schema? Currently, I am only seeing a promise inside. I'm using async/await correctly, but why does it seem like I'm getting just a promise? I als ...

Ways to display a different div when clicking on a div?

Good afternoon, I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue. My problem involves a div with the class .title3. I want another div with the class .Content ...

Guidelines for creating an auto-scrolling React Native FlatList similar to a Marquee

I currently have a FlatList component set up in my project. <FlatList horizontal data={data} key={(item, index) => index.toString()} ListHeaderComponent={listHeader} renderItem={ // renderin ...

Steps for Deactivating Past Dates on JQuery Datepicker1. Open your

I've been working on a custom JQuery Calendar for selecting appointments, with the requirement to disable dates prior to the current date and highlight available dates in an orange color (#f48024). Unfortunately, my attempt using minDate hasn't b ...

What is causing the issue with dynamic special characters not functioning properly in my React router?

I am working with 3 components named App.js, SearchCategoryPage.js, and Home.js. However, when I click on the search icon, it does not navigate me to the search page. What could be the reason for this issue? App.js const outlet_id = useSelector((state) =& ...

Troubleshooting a visual problem using react-easy-crop within a React MUI Dialog

I'm having trouble adjusting the layout of MUI Dialog in combination with react-easy-crop. My goal is to achieve a perfect display of the dialog using react-easy-crop. However, the react-easy-crop component is covering the entire dialog. I attempted t ...

Using jQuery to smoothly scroll to a position determined by a custom variable

Here's the script I am working with: $('.how-we-do-it .items div').on('click', function () { var $matchingDIV = $('.how-we-do-it .sections .section .content div.' + $(this).attr('class')); $matchingDIV. ...

The setState function in ReactJS seems to be failing to properly update the fields

I am having trouble resetting the value of my input type to empty after storing data from a controlled form element. The first method below is not working for me, even though I'm using setState to clear the input fields. Can someone help me understand ...

Building a personalized Directive in Angular: A step-by-step guide

I attempted to implement a sample pagination feature by creating a directive like the following (I am not sure if it is correct): (function() { app.directive("myPagination", function() { return { restrict: 'E', templateUrl: & ...

Having trouble with Vue 3 Component State not updating following an asynchronous operation?

Encountering challenges in my Vue 3 app when trying to update a component's state post an asynchronous operation. Here's what's happening: Within a component, there is a method called containerMoveHere that utilizes Socket.io for an async o ...

What is the best way to prevent the first option in a <select> element from moving up and down using jQuery?

Is there a way to make the first option in a select list non-selectable and keep it at the top when using up and down buttons? The value option should always remain on top. If "Author" is selected and the up button is clicked, nothing should change. The ...

Loading a Vue.js template dynamically post fetching data from Firebase storage

Currently, I am facing an issue with retrieving links for PDFs from my Firebase storage and binding them to specific lists. The problem arises because the template is loaded before the links are fetched, resulting in the href attribute of the list remainin ...

Sign up for the observable, retrieve the asynchronous mapped outcome with input from the dialog, and then utilize the outcome from the map

Currently, I am utilizing an API-service that delivers an Observable containing an array of elements. apiMethod(input: Input): Observable<ResultElement[]> Typically, I have been selecting the first element from the array, subscribing to it, and the ...

Skipping an iteration in ng-repeat in Angular 1.0.8: A simple guide

Is it possible to skip a particular iteration in ng-repeat without modifying the underlying array/object being iterated over? Consider the following example: var steps = [ { enabled: true }, { enabled: true }, { ...

Having trouble with Angular NgbModal beforeDismiss feature?

My goal is to add a class to the pop up modal before closing it, and then have it wait for a brief period before actually closing. I've been trying to do this using the beforeDismiss feature in the NgbModalOptions options in Angular Bootstrap's d ...

Lack of intellisense support for .ts files in Visual Studio Code

Currently, I am using Visual Studio Code 1.17.2 on Arch Linux to kickstart my work with Node.js/Angular4. To avoid confusion caused by loosely typed code, I have decided to switch to TypeScript for my NodeJS server as well. This is why my main file is name ...

Display the outline of a translucent image

Looking to create an image reveal effect on my website. I want to display only the outline of a transparent image using brightness, then gradually reveal the full image by removing the brightness effect. Currently, I achieve this with a black outline usi ...

Retrieve the width of an element once the browser has finalized its dimensions

I am facing an issue with centering a pop-up box perfectly within the window using CSS properties. The code for the pop-up box styling is as follows: #pop_up { position: fixed; display: inline-block; border: 2px solid green; box-shadow: 0p ...