-3

I got a question, I'm struggling with keycodes.

If i press at the "-" key my text box will filled with "-".

if (e.altKey && e.keyCode == 13 || e.keyCode == 173) {
                document.getElementById("uitkomst").value += "-";
            }

I want to fill my textbox with *. There is no specific keycode for * The keycodes for 8 and * are the same. How can I find a way for typing * in my textbox?

Goks
  • 9
  • 8

1 Answers1

2

Don't use keyCode, use key and compare with *.

if (e.altKey && e.key === '*') {
  document.getElementById("uitkomst").value += "*";
}

keyCode (just as the proprietary event.which) is deprecated and cannot be implemented in a cross-OS, cross-browser and cross-internationalized way. For example the German keyboard has * left of the enter key and needs to be accessed using SHIFT.

By the looks of it you're creating a calculator. I'd suggest you list the allowed characters in an array:

const allowedKeys = '+-/*.,0123456789%'.split('');
allowedKeys.push('Enter');
allowedKeys.push('Backspace');
allowedKeys.push('Delete');
allowedKeys.push('ArrowLeft');
allowedKeys.push('ArrowRight');
allowedKeys.push('ArrowUp');
allowedKeys.push('ArrowDown');

const allowedKeysWithCtrl = 'acvx'.split('');
allowedKeysWithCtrl.push('Home');
allowedKeysWithCtrl.push('End');
allowedKeysWithCtrl.push('PageDown');
allowedKeysWithCtrl.push('PageUp');

calculator.addEventListener('keydown', function(e){
  if (!e.ctrlKey && allowedKeys.includes(event.key)) return;
  if (e.ctrlKey && allowedKeysWithCtrl.includes(event.key)) return;
  e.preventDefault();
})
<textarea id="calculator"></textarea>
connexo
  • 53,704
  • 14
  • 91
  • 128
  • doesn't work for me, if i press * it doesn't add it to the textbox. – Goks Jan 15 '20 at 12:56
  • @Goks Which browser are you using? The Javascript uses a syntax only understood by evergreen browsers (no version of IE). Let me rewrite it for compatibility with old browsers. Edit: Done. – connexo Jan 15 '20 at 12:59
  • No sir, I'm using Mozilla Firefox. – Goks Jan 15 '20 at 13:02
  • I used the" if (e.altKey && e.key === '*') { document.getElementById("uitkomst").value += "*"; }" you wrote. if I press * nothing happens. – Goks Jan 15 '20 at 13:05
  • 1
    You don't want to check for `altKey`. Remove that. On German keyboards, you access `*` with Shift. No need to check for which key was pressed - only which character that is supposed to generate. Also, instead of adding the character to the textbox' value yourself, simply allow the keyboard event to happen if a legal character was entered. Otherwise, use `e.preventDefault` and no character will appear. – connexo Jan 15 '20 at 13:10