0

I need to detect any "@"-inputs into a textfield but have no idea how to get that information as two keys have to be pressed to write the @-sign.

And I don't even know if these keys are the same in every country so basically I'm asking if there's a way to check the last typed character (without checking the keys).

Julius S.
  • 664
  • 9
  • 21
  • Do you really need to detect the *last typed character*, or would it be fine to find `@` anywhere in the field? – Bergi May 13 '17 at 08:05
  • Yes, as a menu has to popup everytime, the user types the @-sign. – Julius S. May 13 '17 at 08:12
  • I know but then I wouldn't handle the case when the user moves the cursor "inwards" and types @. – Julius S. May 13 '17 at 08:14
  • create a "keyup" or "keydown" event listener for the input field using jQuery, then wrap the function that the event listener calls with a debounce function that would check the entry of the field for the '@' using a simple regex expression. – lasec0203 May 13 '17 at 08:15
  • Hm, I see. So no that wouldn't solve your problem then – jeremye May 13 '17 at 08:17
  • I could save the number of occurence of the @ sign in a variable and open the menu everytime the count gows up but I think this would be a bit overkill as with every change on the textfield the whole text had to be scanned (max. 650 chars), I don't know if this is a performance issue. – Julius S. May 13 '17 at 08:18
  • Check out this question, I think it has you covered: http://stackoverflow.com/questions/1846599/how-to-find-out-what-character-key-is-pressed. Or the answer below works... – jeremye May 13 '17 at 08:19

1 Answers1

2

Pretty simple:

const input = document.getElementById('input');

input.addEventListener('keydown', function(e) {
  if (e.key === '@') alert('@ typed!');
})
<input type="text" id='input'>

The typed character is stored inside event.key property passed to the event handler.

Egor Stambakio
  • 17,836
  • 5
  • 33
  • 35