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.

2

1 Answer 1

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>

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.