简体   繁体   中英

Make search case insensitive

Below in the JSFiddle link I have a project for a country selection filter.

In the search bar you can fill out a country you want in your filter. However it only works if you use lowercases. I tried to edit my css to transform the text into lowercase but whenever you use capitals it still doesnt work. So I think ill have to adjust the script.

However I don't know how to make this script case insensitive. Can you help me out? 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");
              }
        });
    });

The elem.value in the keyup handler block is all lowercase. As such, to make the match case-insensitive you need to convert the value the user typed lowercase too by using query.toLowerCase() . Try this:

$('#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");
        }
    });
});

use below code use query.toLowerCase() to convert text in to 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");
          }
    });
});

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