Jquery Autocomplete case sensitive for utf-8 characters

后端 未结 2 746
日久生厌
日久生厌 2021-01-21 05:58

I am using jquery autocomplete plugin to search in a long list of names. It works fine for all latin and english characters, but with turkish characters I have problems, as the

相关标签:
2条回答
  • 2021-01-21 06:27

    I would recommend taking a look at the accent map demo on the jQueryUI examples page. The idea in the demo is to map accent characters to non-accented characters using a hash. I would change your code to look like that demo:

    $("#PROVINCE_AC_LEFT_autocomplete_label").autocomplete({
        source: function(request, response) {
            var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
            response($.grep(tags_PROVINCE_AC_LEFT, function(value) {
                value = value.label || value.value || value;
                return matcher.test(value) || matcher.test(normalize(value));
            }));
        },
        select: function(event, ui) {
            var selectedObj = ui.item;
            $("#PROVINCE_AC_LEFT_autocomplete_label").val(selectedObj.label);
            $("#PROVINCE_AC_LEFT").val(selectedObj.value);
            return false;
        },
        focus: function(event, ui) {
            $(this).val(ui.item.label);
            return false;
        }
    });
    

    Example: http://jsfiddle.net/gZ8xz/

    (I've only added a few character mappings in the demo)

    0 讨论(0)
  • 2021-01-21 06:32

    After years from the last reply, I just ran into the same problem.

    Accent mapping is not good enough for Turkish because it is still matching "I" with "i" and vice versa. However, lowercase "I" is "ı" and uppercase "i" is "İ" in Turkish. So, when I type "I", "İzmir" should NOT be a match and when I type "İ", "Iğdır" should NOT be a match.

    So I used the following:

    function toLowerTurkish(str) {
      var letters = {
        'Ç': 'ç', 'Ğ': 'ğ', 'I': 'ı', 'İ': 'i', 'Ö': 'ö', 'Ş': 'ş', 'Ü': 'ü',
      };
      str = str.replace(/(([ÇĞIİÖŞÜ]))/g, function(letter) { return letters[letter]; });
      return str.toLowerCase();
    }
    
    function containsTurkish(txt, str) {
      return toLowerTurkish(txt).indexOf(toLowerTurkish(str)) >= 0;
    }
    
    var itemList = [
      { label: 'İzmir',    value: 'İzmir' },
      { label: 'istanbul', value: 'istanbul' },
      { label: 'Iğdır', value: 'Iğdır' },
      { label: 'ısparta', value: 'ısparta' }
    ];
    
    function autocompleteSourceTurkish(request, response) {
      var matchList = [];
      itemList.forEach(function(item, index) {
        if (containsTurkish(item.label, request.term)) matchList.push(item);
      });
      response(matchList);
    }
    
    $(function() {
      $('#itemMenu').autocomplete({
        source: autocompleteSourceTurkish
      });
    });
    

    http://jsfiddle.net/emfy5gf9/

    0 讨论(0)
提交回复
热议问题