Search code examples
javascriptuppercaselowercasesearch-form

How can I make my search form work with uppercase and lowercase


I want my search form to work with uppercase and lowercase. So whenever I input something that's lowercase it will also show me te uppercase results in the table I'm searching in.

Here's my javascript

function searchFunction() {
var searchText = document.getElementById('database_search_bar').value;
var targetTable = document.getElementById('database_table');
var targetTableColCount;

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

    if (rowIndex == 0) {
       targetTableColCount = targetTable.rows.item(rowIndex).cells.length;
       continue; 
    }

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

    if (rowData.indexOf(searchText) == -1)
        targetTable.rows.item(rowIndex).style.display = 'none';
    else
        targetTable.rows.item(rowIndex).style.display = 'table-row';
}

Can anyone help me with this?


Solution

  • Change this line:

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

    to:

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

    This way, for comparison, you will be using lower case strings only. I.e. if searchText was "Lorem Ipsum" and rowData was "I HAVE LOREM IPSUM WITHIN", they'll become "lorem ipsum" and "i have lorem ipsum within" respectively - thus, they'll match.

    String.prototype.toLowerCase() reference.

    Also note that in ES6 you have String.prototype.includes() that might be used for what you're doing. It'll read a bit better - however it's not supported in IE at the moment.