0

I want to search a table in my html for a term. I have the code for that but it does not take alternatives like when I type in "what is that" it searches for "what is that" and not e.g. "What is that".

Also I want when I add a space at the end that the script ignores it and only goes for text chars.
Here is the fiddle: jsfiddle.net/x7aUy/4
Here is the code:

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 table rows = 0 then show no results text

            if (rowIndex <= 1)
            {
                document.getElementById('noresults').style.display = "block";
            }

        }

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

        }           
        else {
            targetTable.rows.item(rowIndex).style.display = 'table-row';
            document.getElementById('noresults').style.display = "none";
            }
    }
}
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
d0ve
  • 63
  • 1
  • 1
  • 11

1 Answers1

0

If i understand, what you want is a non case-sensitive search ?

If yes, then just do a toLowerCase() on both of your data.

At this line :

if (rowData.indexOf(searchText) == -1){}

Just do

if (rowData.toLowerCase().indexOf(searchText.toLowerCase()) == -1){}

Then, 'searchString' will match 'searchstring' or 'SeaRCHsTRINg'

And if you want to remove the whitespace, juste add a regex filter on the input :

searchText = searchText.replace(/^\s+|\s+$|\s+(?=\s)/g, "");

(Credits to Regular expression for removing whitespaces for this one)

Community
  • 1
  • 1
Larta
  • 406
  • 2
  • 9
  • thanks the first thing helped but the second not really :( I want the delete the white space in front and behind the entries. – d0ve Jul 23 '14 at 08:11