0

I have user keypress and keydown to get the current key pressed, but it won't work on touchscreen.

I figured that I need to use .on('input') but how do I get that input?

In other words. I need this to work on a touchscreen:

$('#newtags').keypress(function(e){ 
  if (e.which==13 || e.which==32 || e.which==188){ 
    Do something
  }
});

UPDATE: Thank you for you input. I have used the method where i check the input-fields last character, and remove the last character when function runs:

$('#newtags').on('keyup', function(e){
  var valueofinput= $(this).val();
  var lastcharofinput = valueofinput.substr(valueofinput.length - 1);

  if (e.which==13 || e.which==32 || e.which==188 || e.which==190 || lastcharofinput==' ' || lastcharofinput==',' || lastcharofinput=='.'){
    if (lastcharofinput==' ' || lastcharofinput==',' || lastcharofinput=='.'){
      valueofinput = valueofinput.substr(0, valueofinput.length - 1);
    }
  }
});
LittleWiz
  • 3
  • 2
  • Can you provide code sample to help others understand your problem? – MEDZ Jan 12 '20 at 16:34
  • $('#newtags').keypress(function(e){ if (e.which==13 || e.which==32 || e.which==188){ – LittleWiz Jan 12 '20 at 16:37
  • You can also look at the Value and review the last character, and look for `" "` or `"-"` instead. Touchscreen devices use a virtual keyboard, so some of the same events don't trigger. You might consider one of the Mobile frameworks that can help capture those events in the same way a desktop browser does. – Twisty Jan 12 '20 at 17:02

1 Answers1

0

Similar to your question, the following can be reviewed: keyup, keydown and keypress events not working on mobile

$('#newtags').on('keydown', function(e){ 
  switch(e.which){
    case 13:
      console.log("Enter Pressed.");
      break;
    case 32:
      console.log("Space Pressed.");
      break;
    case 188:
      console.log("Dash Pressed.");
      break;
  }
});

You can use if() as well, switch() can be helpful for multiple scenarios.

Twisty
  • 30,304
  • 2
  • 26
  • 45