在输入时附加带有转换字符的输入字段,JQUERY

Append input field with converted characters as you type, JQUERY

这一定很简单,但由于我的 jQuery 技能很差,我真的卡住了,无法解决。

目标是在用户在输入字段中键入时将拉丁字符转换为大写希腊字符。

看来我已经很接近了,但我的问题是我将拉丁字符和希腊字符放在一起以进行单个 keyup 事件。这是我的fiddlehttps://jsfiddle.net/harman79/dymtufy8/

HTML:

<input type="search" id="search-id">

JQUERY:

$("#search-id").bind('keyup', function(e) {
  var charMap = {
    65: 913,
    66: 914,
    67: 936,
    68: 916,
    69: 917,
    70: 934,
    71: 915,
    72: 919,
    73: 921,
    74: 926,
    75: 922,
    76: 923,
    77: 924,
    78: 925,
    79: 927,
    80: 928,
    81: 931,
    82: 929,
    83: 931,
    84: 932,
    85: 920,
    86: 937,
    87: 937,
    88: 935,
    89: 933,
    90: 918
  };

  $.each(charMap, function(index, value) {
    if (index == e.which) {
      $("#search-id").val(function(index, val) {
        return val + String.fromCharCode(value);
      });
    }
  });
});

如果我将 return val + String.fromCharCode(value); 替换为 return String.fromCharCode(value);,我只会得到转换后的字符,但每个新的 keyup 都会替换以前的输入内容。

如有任何帮助,我们将不胜感激! 哈利

你可以试试这个:

$("#search-id").bind('keyup', function(e) {
  var charMap = {
    65: 913,
    66: 914,
    67: 936,
    68: 916,
    69: 917,
    70: 934,
    71: 915,
    72: 919,
    73: 921,
    74: 926,
    75: 922,
    76: 923,
    77: 924,
    78: 925,
    79: 927,
    80: 928,
    81: 931,
    82: 929,
    83: 931,
    84: 932,
    85: 920,
    86: 937,
    87: 937,
    88: 935,
    89: 933,
    90: 918
  };

  $.each(charMap, function(index, value) {
    if (index == e.which) {
      $("#search-id").val(function(index, val) {
        // Remove last character and replace with new value
        return val.substring(0, val.length - 1) + String.fromCharCode(value);
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="search" id="search-id">