Jump to content

Recommended Posts

Good Afternoon, 

 

I wonder if someone could help. I'm looking at the filter/search table 'How To', here: https://www.w3schools.com/howto/howto_js_filter_table.asp

Ideally, we would like to create a table that is searchable across all columns, is this possible? At the moment I can see how to make it search column 1 or column 2, I would ideally like it to search both. Using the example on the 'How To' page it would mean that someone could search either a name or a country and they would see the results they wanted. 

TIA. 

Link to post
Share on other sites

It would be helpful to learn Javascript instead of copying code, because the change is not very difficult to do if you know Javascript.

You just have to loop through the table cells in a row instead of selecting just one of them:

  // Declare variables
  var input, filter, table, tr, tds, td, i, j, txtValue, found;
  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++) {
    tds = tr[i].getElementsByTagName("td");
    
    // Determine if the value was found in any of the cells
    found = false;
    for(j = 0; j < tds.length; j++) {
      td = tds[j];
      txtValue = td.textContent || td.innerText;
      found = txtValue.toUpperCase().indexOf(filter) > -1;
      if(found) break;
    }
    
    // Update the row if the value was found
    if(found) {
      tr[i].style.display = "";
    } else {
      tr[i].style.display = "none";
    }
  }

 

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...