简体   繁体   中英

Multiple search from HTML table

function doSearch() {
   var searchText = document.getElementById('searchTerm').value;
   var targetTable = document.getElementById('dataTable');
   var targetTableColCount;

   // Loop through table rows.
   for (var rowIndex = 0; rowIndex < targetTable.rows.length; rowIndex++) {
      var rowData = '';

      // Get column count from header row.
      if (rowIndex == 0) {
         targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
         continue; //do not execute further code for header row.
      }

      // Process data rows. (rowIndex >= 1)
      for (var colIndex = 0; colIndex < targetTableColCount; colIndex++) {
         rowData += targetTable.rows.item(rowIndex).cells.item(colIndex).textContent;
      }

      // If search term is not found in row data then hide the row, else show.
      if (rowData.indexOf(searchText) == -1)
         targetTable.rows.item(rowIndex).style.display = 'none';
      else
         targetTable.rows.item(rowIndex).style.display = 'table-row';
   }
}

This code working great for searching one keyword, but I want to search multiple keywords separated by semicolon (;).

first make your function doSearch with a parameter. instead of :

function doSearch() {
        var searchText = document.getElementById('searchTerm').value;

put

function doSearch(searchValue, rows) {...} 

Then do

var keywords = document.getElementById('searchTerm').value.split(';');

And loop over the function doSearch(keyword[index], rowIndexes);

to contain all the keywords

let the function doSearch() return an array with the rowindexes that match. and pass it to the next call, until all the keywords finish.

the last result will be the rowindexes that match all the keywords.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM