Javi Qualms Pdog
Javi Qualms Pdog

Reputation: 55

How to get keys pressed before enter with jQuery

Sorry if this question has already been asked, I am trying to create an app where the user scans a bar code and the data is then shown on the screen. I don't want to use textbox's because I don't want the data to be editable.

So far I've managed to get the enter key which is automatically sent at the end of the barcode but can't seem to get the keys pressed before, any help would be massively appreciated!

var item = "";
$(document).keypress(function(e) {
  if(e.which == 13) {
    alert(item);
  }else{
    item  = item + e.which();
  }
});

Just to clarify what I want to do is show an alert box with the keys pressed before enter! For example : A B C D ENTER would show an alert("ABCD")

Thanks!

UPDATE

So got my code to work but I'm getting "undefinedTHEKEYSPRESEDHERE" as the return:

var counter = 0;
var item = [];
$(document).keypress(function(e) {
  if(e.which == 13) {
    alert(item[counter]);
    counter++;
  }else{
    item[counter] = item[counter] + String.fromCharCode(e.which);
  }
});

Obviously this isn't clear enough, so I've outlined my problem below:

What I'm getting from alert(item[counter]);:

undefinedKEYS

What I want from alert(item[counter]);:

KEYS

So from undefinedKEYS to just KEYS I need to remove the text "undefined".

Clear enough?

Upvotes: 0

Views: 69

Answers (3)

vsync
vsync

Reputation: 130215

Copy paste to your console and run:

var keys = [];
$(document).keypress(function(e) {
  var keyChar;
  if(e.which == 13) {
    console.log( keys.join('') );
    keys.length = 0;
  }
  else{
    keyChar = String.fromCharCode(e.which);
    if( keyChar )
      keys.push( keyChar );
  }
});

This technique will not show keys which does not have a textual character assigned to them (like the F1-F12 keys for example)

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

  1. Not that I recommend this way of checking for previous results, but you are basically resetting item to "" inside the keypress event. Set it once outside the event.

  2. which is a property, not a method:

  3. Convert from ASCII to string char with string.fromCharCode (A google search would have given you that in two seconds).

  4. Use (e.which || e.keyCode) to ensure you get the keycode on all browsers.

e.g.

var item = "";
$(document).keypress(function(e) {
  if((e.which || e.keyCode) == 13) {
    alert(item);
  }else{
    item  = item + String.fromCharCode(e.which || e.keyCode);
  }
});

Upvotes: 1

Curtis
Curtis

Reputation: 103348

Change e.which() to String.fromCharCode(e.which).

http://jsfiddle.net/8msksn3a/

var item = "";
$(document).keypress(function(e) {
  if(e.which == 13) {
    alert(item);
  }else{
    item  = item + String.fromCharCode(e.which);
  }
});

Upvotes: 3

Related Questions