1

I try to write a JavaScript on a html button element. But it will cause the page reload. But when I use input with button type it works just fine. What is the reason for this and why could i can not use button element here?

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Default</title>
<script type="text/javascript">
    function changeTheText() {
        document.getElementById("paragraphText").innerHTML = "The text is changed!";
    }
</script>
</head>
<body>
<form id="form1" runat="server">
<div>    
    <p id="paragraphText">This is awesome!</p>

    <button onclick="changeTheText()">Change the text</button>

    <input type="button" onclick="changeTheText()" value="Click" />
</div>
</form>

TaroYuki
  • 147
  • 3
  • 16

2 Answers2

1

The default behavior of all buttons in a form is to submit unless it is specified otherwise. You can place the button tag outside the form tags to avoid this behavior.

This is largely browser related. IE, especially, has some awkwardness associated with buttons. You can easily search for the differences between the two types of buttons. Here are a couple of good places to start.

http://web.archive.org/web/20110721191046/http://particletree.com/features/rediscovering-the-button-element/

<button> vs. <input type="button" />. Which to use?

Hope that helps.

Community
  • 1
  • 1
pparas
  • 549
  • 4
  • 13
  • Thanks, I just figured out that or I could just change the button type in the tag like button = "button". – TaroYuki Jun 14 '16 at 21:51
0

Use:

event.preventDefault();

to avoid to submit the form and so page reload.

I sugggest you a different way to write your javascript code:

function changeTheText(evt, selector) {
  var e = evt || window.event;
  document.getElementById(selector).innerHTML = "The text is changed by : " + e.target.tagName + "!";
  e.preventDefault();
}
<form id="form1" runat="server">
    <div>
        <p id="paragraphText">This is awesome!</p>

        <button onclick="changeTheText(event, 'paragraphText')">Change the text</button>

        <input type="button" onclick="changeTheText(event, 'paragraphText')" value="Click" />
    </div>
</form>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61