3

I just found out that every time onclick event for my <button> placed inside <form> tag triggers, form submits it's data as if i clicked <input type='submit'>. I don't want that. Buttons inside my form serve other task, form shouldn't submit data after i clicked one of them.

To be more clear, i want this code:

<form action="http://www.google.com" method="POST">
    <button onclick="alert('hi!')">Button</button>
    <br>
    <input type="submit" value="submit"/>
</form>

to show alert "hi!" when i click on the Button and it shouldn't open Google after that. It should only show Google when i press "submit".

Alehar
  • 639
  • 5
  • 16
  • Esailija, it depends on a browser i think because i tested in in Chrome before i posted it in here and it redirects me to Google all right. – Alehar Jun 27 '12 at 10:01
  • Yes I just realized that, different browsers can assume different `type` because you didn't specify it – Esailija Jun 27 '12 at 10:02
  • possible duplicate of [HTML button to NOT submit form](http://stackoverflow.com/questions/2825856/html-button-to-not-submit-form) – Jayarathina Madharasan Mar 25 '15 at 16:23

3 Answers3

10

Specify type="button":

<button type="button" onclick="alert('hi!')">Button</button>

From the linked article:

This [submit] is the default if the attribute is not specified

Esailija
  • 138,174
  • 23
  • 272
  • 326
  • Both answers worked, thanks a lot. I think this one is the best because it helps understanding why i had that problem in the first place. – Alehar Jun 27 '12 at 10:07
  • 1
    @Alehar this should work (the button not submitting form) even if javascript is disabled, since `return false` is dependent on javascript being enabled – Esailija Jun 27 '12 at 10:08
  • yeah sorry didn't see this question. hence +1 from me – Houman Jul 22 '12 at 10:24
2

Try this..

onclick="alert('hi!'); return false;"
hriziya
  • 1,116
  • 1
  • 23
  • 41
1

With jQuery use a span rather than an input, put use the .button call and then set a click event.

Andrew Rhyne
  • 5,060
  • 4
  • 28
  • 41