Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit Search on Enter Key?

Tags:

forms

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>
like image 273
John R Avatar asked Oct 23 '25 21:10

John R


1 Answers

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.

like image 174
Ismael Sarmento Avatar answered Oct 26 '25 02:10

Ismael Sarmento