0

I am editing a code from here to make an alphabet convert into another set alphabet, in other words, my intention is to make an online textarea keyboard for a foreign alphabet.

This is my code which I have edited from above:

<textarea id="txt"></textarea>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$('#txt').on('keypress', function (e) {
    var pressedKey = String.fromCharCode(e.keyCode);
    var $txt = $('#txt');
    e.preventDefault();
if(pressedKey == 'q') {$txt.val($txt.val() + 'ф');}
if(pressedKey == 'w') {$txt.val($txt.val() + 'ц');}
if(pressedKey == 'e') {$txt.val($txt.val() + 'у');}
if(pressedKey == '') {$txt.val($txt.val() + '');} .......
});
</script>

For every latin alphabet there is one cyrillic alphabet. Considering there are uppercase letters and punctuation marks as well, there are certainly a lot of 'if(pressedKey == '') {$txt.val($txt.val() + '');}'s to make.

How can I simplify this code, instead of making more than 50 rows of almost the same line?

I have referred to many sources and have tried many approaches with my short knowledge, I also tried to include var into my Javascript as many sources recommended doing so, but cannot think of a good way. Any help will be greatly appreciated.

Henry
  • 154
  • 10
  • 1
    **Don't use that snippet.** You should not change the behavior of typing inside a textarea. Just for example, Insert some characters, now move to the first charater with your caret. insert a character. Where is your caret now? c'mon ;) – Roko C. Buljan Jan 04 '21 at 10:51
  • 1
    Solution for @RokoC.Buljan valid issue with using `$txt.val(...)`: https://stackoverflow.com/a/4605347/2181514 – freedomn-m Jan 04 '21 at 10:57
  • @RokoC.Buljan thanks for your advice – Henry Jan 04 '21 at 11:00

1 Answers1

2

Use a object and use the pressedKey as key, like:

const characters = {
  'q': 'ф'
}
const newCharacter = characters[pressedKey] || '?'

$txt.val($txt.val() + newCharacter);

Or even less, but you lose a bit of meaning:

$txt.val($txt.val() + ({ 'q': 'ф' })[pressedKey])
Filipe
  • 1,788
  • 2
  • 13
  • 18
  • destructuring (your 2nd example) instead or direct referencing is always a less better idea. Writing *cool* code does not mean it's the ideal or even more readable way to go. – Roko C. Buljan Jan 04 '21 at 10:54