eaglei22
eaglei22

Reputation: 2830

How to determine which "+" key was pressed?

I have a request to replicate the + key as the tab key when the plus key on the number pad side is pressed.

It seems the plus key above letters where shift key is needed, and the plus key where numbers are in a keypad configuration both have a numeric number of 43.

How can I determine which + key was depressed?

Update: I was using this example, "https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_event_key_keycode" as pointed below this was not the correct way to do it.

Upvotes: 4

Views: 73

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337646

The keycodes for each key is different. Numeric keypad = 107, top row = 187

You can use this to verify it on your own keyboard:

$('#text').on('keydown', function (e) {
  $('label').text(e.which);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" />
<label></label>

You can also use the key property in modern browsers (IE9+) to detect which key was output without having to worry about exactly which keys were used to generate it:

$('#text').on('keydown', function (e) {
  if (e.key == '+')
    console.log('You typed a plus symbol!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="text" />
<label></label>

Upvotes: 6

Scott Marcus
Scott Marcus

Reputation: 65845

The two keys produce two different key codes. You can test for the correct one:

$(document).on("keydown", function(evt){
  switch (evt.keyCode){
    case 107:
      console.log("You pressed '+' on the number pad");
      break;
    case 187:
      console.log("You pressed SHIFT '+' on main keyboard");
      break;    
  }     
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Just click once over here to give the "document" focus and then press the + key(s)

Upvotes: 1

Related Questions