1

Let's say I have an input box, <input id="some_input" type="text"/>, and the website is used on a mobile device. I don't want the user to always have to press the "Go" button to do something with the text, it would be much better if the user could simply press the enter key on their phone keyboard. How would I do this?

PG Cubing
  • 11
  • 5

2 Answers2

0

You can do something like this. Apart from using keyup, you could also use keypress or keydown. Same/similar question on Stackoverflow : Javascript enter key pressed event alternative for mobile site

<!DOCTYPE html>
<html>
<body>
  <input type="text" id="some_input">
  <script>

     var x = document.getElementById("some_input");
     x.addEventListener('keyup', function (e) {
          if (e.keyCode === 13) {    
             alert('enter key pressed');    
          }
     }, false);
   </script>
  </body>
  </html>
Sagar Agrawal
  • 639
  • 1
  • 7
  • 17
  • Oh, didn't realize this would also work for mobile devices. Thanks! – PG Cubing Sep 22 '19 at 10:54
  • yes it does. You can simply create a small jsFiddle and open in mobile and alert the value that you will get when pressing the Go/Return button on mobile. It's usually CR and/or LineFeed (LF). – Sagar Agrawal Sep 22 '19 at 10:57
  • Another example on same lines: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_trigger_button_enter – Sagar Agrawal Sep 22 '19 at 11:01
0
document.getElementById("some_input")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
       // call the function
    }
});
  • 2
    A code-only answer is a low-quality answer. Add some explanation as to why you think this code-snippet would work. – Taslim Oseni Sep 22 '19 at 11:11