0

How can I execute some code when the Enter key is hit on a text field?

My approach doesn't do anything:

<script>
textfield.onkeydown = function(e) {
    if (e.keyCode == 13) {
        alert("abc");
    }
}
</script>

<input type="text" id="textfield">

PS: I don't want to use JQuery.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181
  • No it does not. The accepted answer is vanilla/plain js - it is however using 2 ways to get the event and 2 ways to get the keyCode as mandated by the browser differences when not using jQuery. That and assigning after the element is available in the DOM is what you need – mplungjan Nov 01 '15 at 21:29

1 Answers1

1

Put the script below the textfield so that it exists in the DOM first:

<input type="text" id="textfield">
<script>
textfield.onkeydown = function(e) {
    if (e.keyCode == 13) {
        alert("abc");
    }
}
</script>
andrrs
  • 2,289
  • 3
  • 17
  • 25