How to call function on enter key press with html

Issue

I have this markup:

<input type="text" placeholder="...">
<button type="button" onclick="newInput();">Enter</button>

And I want to know how to call my function by typing enter instead of having to actually press the button?

How could you do this?

Edit: this can be done with JS using event listeners but I want to know if you can call the function in pure HTML.

Solution

I used a "submit" event listener on your form. You have to call preventDefault() on the event, in your function, so the default behaviour of the form submitting is avoided.

Please see snippet below

function newInput(e){
  e.preventDefault();
  alert('Function called');
}

// The form element
var form = document.getElementById("submitForm");

// Attach event listener
form.addEventListener("submit", newInput, true);
<form id="submitForm">
    <input type="text" placeholder="...">
    <button type="submit">Enter</button>
<form>

EDIT : Regarding your edit, you can also use the "onsubmit" attribute on the form element :

function newInput(){
  alert('Function called');
}
<form onsubmit="newInput()" id="submitForm">
<input type="text" placeholder="...">
<button type="submit">Enter</button>
<form>

Answered By – Lucas Roquilly

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.