Search code examples
jquerykeyup

Append input field with converted characters as you type, JQUERY


This must be so easy but I am really stuck and cant work it out due to my poor jQuery skills.

The goal is to convert latin characters to capital greek characters as the user types in an input field.

It seems that I am pretty close, but my problem is that I get both my latin and greek characters together for a single keyup event. Here is my fiddle https://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);
      });
    }
  });
});

If I replace return val + String.fromCharCode(value); with return String.fromCharCode(value); I only get my converted character but each new keyup replaces previous input contents.

Any hep would be much appreciated! Harry


Solution

  • You can try this:

    $("#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">