Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML form press 'Enter' in an input text cause click on button

http://jsfiddle.net/PCGvG/

Why in this example when I press 'Enter' in the input text, it executes the onclick? While using <input type="button"> doesn't...

like image 733
rascio Avatar asked Dec 03 '22 21:12

rascio


1 Answers

The element <button> has type="submit" by default. See http://www.w3.org/TR/html401/interact/forms.html#h-17.5

Solution: if you don't want the click handler of the button to be called, give it type="button" explicitly.

<form name="myForm">
    <button type="button" id="test">Click</button>
    <input type="text" name="q" />
</form>

(Pressing Enter will still submit the form though, at least on some browsers.)

With regards to your comment that <input type="button"> acts differently: that's right. An input with type="button" acts the same way as a button with type="button", while an input with type="submit" would act the same as a button with type="submit".

like image 146
Mr Lister Avatar answered Mar 15 '23 03:03

Mr Lister