views:

21

answers:

2

Hello everyone,

I am wondering how to set the default button in html page, so that when enter key is pressed, the same effect of button pressed? For example, when we use Google, after entering query string in the middle input box, we can press enter key to get query results (i.e. press enter has the same effect of click "Google Search" button).

Any solutions? I am not sure whether there are different solutions when it is an html button, and when it is the submit button of a html form?

thanks in advance, George

+1  A: 

That's simply done with a <form> element.

For example, if you have something like this:

<form action="something.php" method="post">
<input type="text" name="blah">
<input type="submit">
</form>

and you press enter in the input field, the form will be posted to something.php, ie. the same as if you press the submit button.

houbysoft
What happens if multiple forms in the same html page? Which form's submit button is pressed? :-)
George2
The one you're in, ie if you have two forms with text input fields and you have the cursor in the first one and you press enter, the first form will get submitted.
houbysoft
Thanks, question answered!
George2
+1  A: 

As long as your form is contained inside a <form> tag and you have an input or button of type="submit", it should submit when you hit enter. If those two conditions aren't true, you can use javascript to detect onkeyup for the enter key.

Chris Fletcher
"you can use javascript to detect onkeyup for the enter key" -- can you show me how? Any samples? :-)
George2
And for Form, what happens if multiple forms in the same html page? Which form's submit button is pressed? :-)
George2
submit will trigger parent form.
eugeneK
Sorry, I do not mean a parent form and another child form inside. I mean two forms of the same html element DOM tree level (i.e. the same hierarchy)?
George2
He means: submit will trigger the form where the focus is in.
BalusC