1

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.

  • In particular, this answer: [Trigger a button click with JavaScript on the Enter key in a text box](https://stackoverflow.com/a/155272) – 001 Jun 03 '22 at 11:19
  • If your input, and button, are inside a form that's the default behaviour. – David Thomas Jun 03 '22 at 11:20

1 Answers1

1

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>
Lucas Roquilly
  • 406
  • 2
  • 9