timi_gun
timi_gun

Reputation: 29

Hitting enter instead of clicking submit is not working in JavaScript

I am trying to allow my user to hit enter in the input field which should trigger the same click event as if they had clicked on the "submit" button with their mouse.

document.getElementById("input").addEventListener("keyup", function() {     
    if (KeyboardEvent.code == "13") {                                        
        document.getElementById("button").click();                          
    }
});

However the keycode doesn't work. The content of the function works when I do KeyboardEvent.code != "13" but I don't know how to make it listen to only the enter key.

I have tried looking t other questions on Stackoverflow (notably here), but my code editor is saying those notations are deprecated.

Upvotes: 0

Views: 39

Answers (2)

Andrii Dobrianskiy
Andrii Dobrianskiy

Reputation: 179

I think that the issue is in a misunderstanding of KeyboardEvent.code https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code meaning. In your case, it will always equal undefined. Instead, you need to get the code from the event. See the example below

document.getElementById("input").addEventListener("keyup", function (e) {
  if (e.code === "Enter") {
    document.getElementById("button").click();
  }
});

Upvotes: 1

Ezequiel S. Sandoval
Ezequiel S. Sandoval

Reputation: 170

To handle this behavior in a form you only need to have a form with a submit button:

<form onSubmit="someSubmitFn()" method="post">
  <!-- form elements -->
  <button type="submit">Submit</button>
</form>

You can also try with e.keyCode instead of KeyboardEvent.code:

document.getElementById("input").addEventListener("keyup", function(e) {     
    if (e.keyCode == "13") {                                        
        document.getElementById("button").click();                          
    }
});

Upvotes: 0

Related Questions