29

has the HTML version changed lately (like from ie7 to IE8?) I notice the following change that cause me some troulbe - I am having a code that is similar to this:

<form method="POST" action="/admin/modify">
<input type="text"/>
<button onclick="dosomething()">Press</button>
</form>
<script type="text/javascript">
function doSomething(){
// doesn't matter what actually
}
</script>

What is weired to me in this code is that by pressing the button inside the form, all I want is to perform some javascript action but eventaully it causes the form to be submitted too, even when I am not willing to do it.
So - is it true? and if so how can I perform some java script actoin inside a from but prevent the form from being submitted automatically?

Spiderman
  • 9,602
  • 13
  • 48
  • 56
  • This is not just an issue with IE. This happens on Chrome as well. As per @Pekka's answer, adding type="button" solved this for me. – Joshua Dance Aug 05 '14 at 15:50

2 Answers2

46

According to W3schools, submit is the new default action for button elements in IE 8:

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".

So if you don't specify a type, the form will be submitted in all browsers, but not IE 7.

this should work:

<button type="button" onclick="dosomething()">Press</button>
Pekka
  • 442,112
  • 142
  • 972
  • 1,088
  • 1
    perhaps this link is relevant and answer my question: http://stackoverflow.com/questions/932653/how-to-prevent-buttons-from-submitting-forms – Spiderman Mar 13 '10 at 21:15
  • smoothly it did work. Only to add the type="button". I didn't even had to return false at the end of the command. It didn't occur to me in the previous IE version (IE7) must say. – Spiderman Mar 13 '10 at 21:18
  • lol Pekka, I think you read the quote wrong. W3Schools suggests that in IE the default type is `button`, which is incorrect for IE8. That means, in all browsers except IE7 and lower, a button with no type will submit the form. – Andy E Mar 13 '10 at 21:18
  • @Andy hehe, you're right! Cheers, corrected my answer. @Spiderman that's probably why it didn't occur to you - it's only there since IE8. – Pekka Mar 13 '10 at 21:20
  • This doesn't just happen with IE, had same behavior in Chrome. Adding type="button" solved this issue for me. – Joshua Dance Aug 05 '14 at 15:52
2

From the IE docs for the button element:

Internet Explorer 8 and later. The default value of this attribute depends on the current document compatibility mode. In IE8 mode, the default value is submit. In other compatibility modes and earlier versions of Internet Explorer, the default value is button.

The standard suggests the default type is submit, previous versions of IE incorrectly defaulted to button

Andy E
  • 338,112
  • 86
  • 474
  • 445