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>