views:

105

answers:

4

Hello,

I have a form. Outside that form, I have a button. A simple button, like this:

<button>My Button</button>

Nevertheless, when I click it, it submits the form. Here's the code:

<form id="myform">
    <input />
</form>
<button>My Button</button>

All this button should do is some JavaScript. But even when it looks just like in the code above, it submits the form. When I change the tag button to span, it works perfectly. But unfortunately, it needs to be a button. Is there any way to block that button from submitting the form? Like e. g.

<button onclick="document.getElementById('myform').doNotSubmit();">My Button</button>

Thanks in advance!

A: 

return false; at the end of the onclick handler will do the job.

ThiefMaster
You're a genius! THANKS!
arik-so
Who is downvoting this correct answer...? While type="button" might be cleaner this answer is not incorrect at all.
ThiefMaster
I guess this answer only works when javascript is enabled?
Konerak
Buttons which do not submit forms are only useful with JavaScript enabled anyway... I agree that type="button" is cleaner though.
ThiefMaster
+17  A: 

I think this is the most annoying little peculiarity of HTML... That button needs to be of type "button" in order to not submit.

<button type='button'>My Button</button>
Dave Markle
This is the way.
erikkallen
You're right. THANKS! What I have done is both change the type and add `return false` ^^. Just to make sure.
arik-so
You can feel comfortable about not adding return false at the end of your code. I would recommend taking it out.
Dave Markle
OK, I'll leave it out. Thanks!
arik-so
+3  A: 

It's recommended not to use the <Button> tag. Use the <Input type='Button' onclick='return false;'> tag instead. (Using the "return false" should indeed not send the form.)

Some reference material: http://www.htmlcodetutorial.com/forms/_BUTTON.html

Tim
+1  A: 

Dave Markle is correct. From W3School's website:

Always specify the type attribute for the button. The default type for Internet Explorer is "button", while in other browsers (and in the W3C specification) it is "submit".

In other words, the browser you're using is following W3C's specification.

Gert G