4

What needs to be done to have this form submitted when someone hits the 'enter' key?

<form id="search" onsubmit="javascript:search(document.getElementById('searchText'))">
  <input type='text' id='searchText' autofocus />
  <input type='button' onclick="search(document.getElementById('searchText'))" value='Search' />
</form>
John R
  • 2,920
  • 13
  • 48
  • 62

2 Answers2

8

You can just use a form as below, with input type submit, which in this case, if you press enter in any input - if you had more of them - it will be a default behaviour of the form to be submitted:

<form id="search">
  <input type='text' id='searchText' />
  <input type='submit' value='Search' />
</form>

or, as it shows, you want to use the onsubmit function and handle the "submit" of the form, so you can do this:

<form id="search" action="#">
    <input type="text" id='searchText' name="myinput" onkeypress="handle" />
</form>

<script>
    function handle(e){
        if(e.key === "Enter"){
            alert("Enter was just pressed.");
        }

        return false;
    }
</script>

A code, quite the same, can be found on this similar question: How to capture Enter key press?

Hope I answered your question, even out of time.

FabianCook
  • 20,269
  • 16
  • 67
  • 115
Ismael Sarmento
  • 844
  • 1
  • 11
  • 22
0

This example worked perfectly for me:

var input = document.getElementById("myInput");

// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function(event) {
  // Number 13 is the "Enter" key on the keyboard
  if (event.keyCode === 13) {
    // Cancel the default action, if needed
    event.preventDefault();
    // Trigger the button element with a click
    document.getElementById("myBtn").click();
  }
});

I took the example at w3schools.