使搜索不区分大小写

Make search case insensitive

本文关键字:大小写 不区 搜索      更新时间:2023-09-26

在下面的JSFiddle链接中,我有一个国家选择过滤器的项目。

在搜索栏中,您可以在过滤器中填写您想要的国家/地区。然而,只有在使用小写字母时,它才有效。我试着编辑我的css,将文本转换为小写,但无论何时使用大写,它仍然不起作用。所以我觉得我得调整一下剧本。

但是,我不知道如何使这个脚本不区分大小写。你能帮我吗?https://jsfiddle.net/Sentah/d8so22xj/

$("#countryName").focus(function()
    {
        if ($(this).val() === $(this)[0].title)
        {
            $(this).removeClass("default_text_active");
            $(this).val("");
        }
    });
    $("#countryName").blur(function()
    {
        if ($(this).val() === "")
        {
            $(this).addClass("default_text_active");
            $(this).val($(this)[0].title);
        }
    });
    $("#countryName").blur(); 

    $('#countryName').on('keyup', function() {
        var query = this.value;
        $('[id^="chk_country"]').each(function(i, elem) {
              if (elem.value.indexOf(query) != -1) {
                  elem.style.display = 'inline';
                  $("#lbl_for_" + elem.getAttribute("id")).removeClass("hidden") ;
              }else{
                  elem.style.display = 'none';
                  $("#lbl_for_" + elem.getAttribute("id")).addClass("hidden");
              }
        });
    });

使用下面的代码使用query.toLowerCase()将中的文本转换为LowerCase。

$('#countryName').on('keyup', function() {
    var query = this.value;
    $('[id^="chk_country"]').each(function(i, elem) {
          if (elem.value.indexOf(query.toLowerCase()) != -1) {
              elem.style.display = 'inline';
              $("#lbl_for_" + elem.getAttribute("id")).removeClass("hidden") ;
          }else{
              elem.style.display = 'none';
              $("#lbl_for_" + elem.getAttribute("id")).addClass("hidden");
          }
    });
});

keyup处理程序块中的elem.value都是小写的。因此,为了使匹配不区分大小写,您还需要使用query.toLowerCase()转换用户键入的小写值。试试这个:

$('#countryName').on('keyup', function () {
    var query = this.value;
    $('[id^="chk_country"]').each(function (i, elem) {
        if (elem.value.indexOf(query.toLowerCase()) != -1) { // note toLowerCase here
            elem.style.display = 'inline';
            $("#lbl_for_" + elem.getAttribute("id")).removeClass("hidden");
        } else {
            elem.style.display = 'none';
            $("#lbl_for_" + elem.getAttribute("id")).addClass("hidden");
        }
    });
});