Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if key pressed is in provided array

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)?

like image 584
Przemek Avatar asked May 05 '26 23:05

Przemek


2 Answers

You could use keypress instead. Like

$("#some-input").bind('keypress', function(e) {
    var availableKeys = [".", ",", ";"];

    if(availableKeys.indexOf( String.fromCharCode( e.which ) ) > -1 ) {
        alert('Derp');
    }
});
like image 147
jAndy Avatar answered May 08 '26 12:05

jAndy


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.

like image 27
Rory McCrossan Avatar answered May 08 '26 12:05

Rory McCrossan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!