Reputation: 281
I'd like to disable the '-' key on an input on keydown.
My first idea was using the usual solution:
if(e.keycode == 189 || e.which == 189 ){
return false;
}
but in fact, the '-' and the ')' has the same keycode on mac (i.e. 189) and I don't want my closing parenthesis key to be blocked as well.
since they have the same keycode, the fromCharCode method is irrelevant here (both awkwardly yielding '½')
is there an alternative?
Upvotes: 0
Views: 54
Reputation: 634
You could use event.key instead of event.keyCode.
window.addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
if (event.key == '-') {
event.preventDefault();
}
}, true);
You can find out more about KeyboardEvents in javascript here on MDN. There is stated that keyCode
and which
are both deprecated.
I've added a more elaborate snippet which shows how to block a key only on a specific element.
document.getElementById("field1").addEventListener("keydown", function (event) {
if (event.defaultPrevented) {
return; // Do nothing if the event was already processed
}
if (event.key == '-') {
event.preventDefault();
}
}, true);
<input id="field1" type="text" />
<input id="field2" type="text" />
Upvotes: 2