www.webdeveloper.com
Results 1 to 6 of 6

Thread: [RESOLVED] Why JavaScript is not working if the submit button is inside a form

  1. #1
    Join Date
    Mar 2014
    Posts
    4

    resolved [RESOLVED] Why JavaScript is not working if the submit button is inside a form

    It is going to be difficult to find reason for this reading tutorials (or googling) so I ask here. Why does not javascript function change the <p> text if the submit button is inside the form but it does work if I move the button outside the form. The text appears but disappears quickly. Seems like the form is somehow updated after change again. See code below (so this code is not working).

    HTML Code:
    <html>
    <head>
    <script>
    function showText()
    {
    	document.getElementById("mytext").innerHTML = "Hello world";
    }
    </script>
    </head>
    
    <body>
    
    <form id="frm1">
    
    <p id="mytext"></p>
    
    <button onclick="showText()">Try it</button>
    </form> 
    
    </body>
    </html>

  2. #2
    Join Date
    Mar 2011
    Posts
    1,141
    Because you didn't set the 'action' attribute on the <form> tag, it defaults to the page itself. So when you click on the button, the form is submitted and the page reloads itself. And since the page is so simple, it's practically instantaneous. The simplest solution is to cancel or negate the <button> action:
    Code:
    <button onclick="showText(); return false;">Try it</button>
    Rick Trethewey
    Rainbo Design

  3. #3
    Join Date
    Mar 2014
    Posts
    4
    Thanks, helps a lot.

  4. #4
    Join Date
    Mar 2014
    Posts
    4
    Thanks, helps a lot.
    I just read more about it, and seems like might be even better use:
    HTML Code:
    <input type='button' value='Try it' onclick="showText()">
    instead of button as it works better on different browsers they say? Doing this anyway does not reload the page. But your message opened this to me.

  5. #5
    Join Date
    Mar 2011
    Posts
    1,141
    It's largely a distinction without a difference. You'll still need the 'return false;' to stop the form submission.
    Rick Trethewey
    Rainbo Design

  6. #6
    Join Date
    Mar 2014
    Posts
    4
    But isn't it that its not needed here as the type='button'. If the type is 'submit' then its needed? I guess in the original button it was submit as well as a default. When I am running this <input type='button' .. without return fals; it works on both browsers. But again, I learned a lot here.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles