jQuery Autocomplete with Special Characters (i.e. ö, Ä, é, or ß)

守給你的承諾、 提交于 2019-12-20 01:05:28

问题


How can I have autocomplete match on words with special characters, such as those in German: ö, Ä, é, or ß. For example, I'd like "mun" to match "München" and "Munchen".


回答1:


There's an excellent article on this at A List Apart which includes some Javascript code

var accentMap = {
  'á': 'a',
  'é': 'e',
  'í': 'i',
  'ó': 'o',
  'ú': 'u'
};

function accent_fold(s) {
  if (!s) {
    return '';
  }
  var ret = '';
  for (var i = 0; i < s.length; i++) {
    ret += accent_map[s.charAt(i)] || s.charAt(i);
  }
  return ret;
};



回答2:


I use typeahead, and after hours of banging my head against a wall it was as simple as using utf8_encode on the script that returns the JSON:

utf8_encode(stripslashes($variable));




回答3:


jQuery UI has a demo for this problem (accent folding) on their site: https://jqueryui.com/autocomplete/#folding

$(function() {
  var names = ["Jörn Zaefferer", "Scott González", "John Resig"];

  var accentMap = {
    "á": "a",
    "ö": "o"
  };
  var normalize = function(term) {
    var ret = "";
    for (var i = 0; i < term.length; i++) {
      ret += accentMap[term.charAt(i)] || term.charAt(i);
    }
    return ret;
  };

  $("#developer").autocomplete({
    source: function(request, response) {
      var matcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
      response($.grep(names, function(value) {
        value = value.label || value.value || value;
        return matcher.test(value) || matcher.test(normalize(value));
      }));
    }
  });
});


来源:https://stackoverflow.com/questions/4402838/jquery-autocomplete-with-special-characters-i-e-%c3%b6-%c3%84-%c3%a9-or-%c3%9f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!