page not redirecting in javascript after clicking a button which is inside a form

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form>
    <button onclick="demo()" name="btn">click here</button>
    </form>
    <script type="text/javascript">
        function demo()
        {
            location.href="http://www.google.com";
        }
    </script>
</body>
</html>

if the button is placed without the form tag it is working properly. If it is placed inside the tags its not getting redirected when clicked on it.

3 answers

  • answered 2018-05-16 05:40 Bdloul

    <html>
    <head>
        <title></title>
    </head>
    <body>
        <form>
        <button onclick="return demo()" name="btn">click here</button>
        </form>
        <script type="text/javascript">
            function demo()
            {
                location.href="http://www.google.com";
                return false;
            }
        </script>
    </body>
    </html>
    

    This modification prevent the default action of clicking on a button inside a form (which is submitting it) and relocate to google.

    If you don't need the form do not use it.

  • answered 2018-05-16 05:41 Negi Rox

    It should be look like this.

    <form>
        <button onclick="demo(event)" name="btn">click here</button>
    
        <script type="text/javascript">
            function demo(e) {
                e.preventDefault();
                window.location.href = "http://www.google.com";
            }
        </script>
    </form>
    

    or you can try this also

    <form>
        <button onclick="demo(event)" name="btn">click here</button>
    </form>
    <script type="text/javascript">
            function demo(e) {
                e.preventDefault();
                window.location.href = "http://www.google.com";
            }
    </script>
    

  • answered 2018-05-16 05:54 Kavian K.

    Always specify the type attribute for a <button> element. Different browsers use different default types for the <button> element.

    If you use the <button> element in an HTML form, different browsers may submit different values. Use <input> to create buttons in an HTML form.

    <form>
      <button type="button" onclick="demo()" name="btn">Click Here</button>
      <!-- or you can use input element -->
      <input type="button" onclick="demo()" value="Click Here" />
    </form>
    
    <script>
    function demo() {
      window.location.href = "http://www.google.com"
    }
    </script>