使搜索文本框输入值不区分大小写

时间:2014-12-08 17:22:17

标签: javascript html

所以我这个表有几行,下面是搜索文本框的代码:

<input type="text" class="textbox" id="searchTerm" onkeyup="doSearch()" placeholder="Search Rares"/>

当用户在文本框中输入文本时,将运行以下脚本。该脚本根据文本框输入隐藏表格的行。

// JavaScript Document

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';
        }
    }

问题是输入不区分大小写,所以如果用户键入&#39; hello&#39;在文本框中,有“你好&#39;在表格中,脚本将隐藏表格的行。

我是Javascript的菜鸟,所以如果有人能帮我修复它,我们将非常感激。

1 个答案:

答案 0 :(得分:0)

在验证搜索结果之前,将输入转换为大写字母,然后在将其与rowData进行比较时,也将其设为大写。

    // JavaScript Document

    function doSearch() {
    //Get the input value as lower case
    var searchText = document.getElementById('searchTerm').value.toUpperCase(); 
    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 (upper case) is not found in row data
        //then hide the row, else show
        if (rowData.toUpperCase().indexOf(searchText) == -1)
            targetTable.rows.item(rowIndex).style.display = 'none';
        else
            targetTable.rows.item(rowIndex).style.display = 'table-row';
    }
}

修改

正如Jakar的评论所指出的,你最好将所有文本转换为大写而不是小写(我最初推荐)。问题是某些字符可能无法正确转换。资料来源:http://msdn.microsoft.com/en-us/library/bb386042.aspx