ng-keyup $event registering wrong keycode
Hi,
I'm checking for upper case for a password field in a form like so:
<input name="password" type="password" ng-model="password" ng-keyup="checkCapsLock($event)" required/>
JS code:
$scope.checkCapsLock = function(ev) {
var kc = ev.keyCode ? ev.keyCode : ev.which;
var sk = ev.shiftKey ? ev.shiftKey : (kc == 16);
if (((kc >= 65 && kc <= 90) && !sk) || ((kc >= 97 && kc <= 122) && sk)) {
alert('Caps lock is on!');
}
};
Now, this reports that Caps lock is on even when it isn't. i.e. if I press 'a', it still registers the key code as 65 ('A'). Have tried in both latest FF and Chrome, both with the same prolem.
This isn't an Angular issue, this is your algorithm, browser, or some other library (possibly jQuery). Angular doesn't make any changes to the keyCode, shiftKey or which properties of the event interface.
I don't think it's the algorithm's fault. I debugged the function, and ev.keyCode == 65 when I press 'a'.
Oh, and I'm not using jQuery. Just pure Angular (jqLite).
You should avoid using keyCode for this anyways, because the keyCode is really the scan code for the device, which is not necessarily universal across all keyboards, and some devices don't report this at all. which is generally the same story here for this reason. The scan code may or may not be the same regardless of the state of shift or capslock.
Anyways, while I'm not sure what happens with IE, in FF, Chrome and Safari, you only get the scan code in keydown and keyup. You need to use keypress to get accurate textual data. However, this is likely to work incorrectly on mobile devices, they're notorious for not reporting things correctly.
Just for completeness, I tried ng-keydown, same error. However, as you suggested, I tried ng-keypress, which worked.
The strange thing is if I'm not using Angular, that function works as expected on keyup.
Trust me, Angular does not touch any of the KeyEvent properties, and your issue is reproducible in a naked jsfiddle (using vanilla DOM apis). Angular is not responsible for the bug here (you can grep the tree for changes to key event properties, they aren't happening --- and in fact, those particular properties are all readonly, so in modern browsers Angular would have a hard time changing them). I'd be very interested to see a reproduction where this behaves differently with vanilla DOM vs angular.
I'm having same issue. keypress returns different keycode that keyup. keyup is always caps-on. I need to capture backspace and keypress does not send these..
Did you read my explanation above, @zenix?
Sure. How's keypress implemented?