I have code similar to this:
$("#some-input").keyup(function (event) {
var availableKeys = [".", ",", ";"];
var key = String.fromCharCode(event.which);
if (availableKeys.indexOf(key) != -1) {
alert("Derp");
}
});
However it does not work as I expected. The event.which/fromCharCode combination works like this properly on digits or letters (capital ones) and this is the correct behaviour since (I presume) event keycodes are different than charset entries.
Is there a workaround other than directly specifying keycodes for comparison (keeping the array of characters is a priority)?
You could use keypress instead. Like
$("#some-input").bind('keypress', function(e) {
var availableKeys = [".", ",", ";"];
if(availableKeys.indexOf( String.fromCharCode( e.which ) ) > -1 ) {
alert('Derp');
}
});
Try changing your array to contain the keycodes of the keys you wish to check for:
$("#some-input").keyup(function(event) {
var availableKeys = [190, 188, 59]; // ".", ",", ";"
if (availableKeys.indexOf(event.which) != -1) {
alert("Derp");
}
});
Example fiddle here
Here's a full list of keycodes
Edit
After a little investigation it appears your method should work, but the implementation of String.fromCharCode is flawed - at least for the symbol keys. While pressing . returns the correct keyCode of 190, when you run that through fromCharCode you get the string ¾. Other keys such as [ and # show similar behaviour. I assume this is due to internationalisation, maybe someone else could confirm.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With