Harshit Agrawal Harshit Agrawal - 21 days ago 8
HTML Question

Onclick inside form element

While fiddling something with the HTML code, I came up with a mind-boggling thing. Have a look at the code:-

<form class="index-form" name="LoginForm">
<div class="index-input">
<button onclick="myFunction();">Login</button>
</div>
</form>
<script>
function myFunction(){
window.location = "https://blahblah.com/auth/?client_id=fdsgsnlr";
};
</script>


This just added a '?' in my URL and did nothing. But when I relieve the button element from the parent form element, it works perfectly fine. I know what I did is just nonsense but still, any idea how and why it's happening?

Answer

When your button is written inside <form> then after calling onclick event handler on button, your form gets submitted. Since there is no action attribute defined in your <form> element so the default is make GET request to the current page with any given named inputs in the form, since you have none, you just get '?'.

Now, if you return false from onclick event handler, then form does not get submitted and your window.location code works.

Update code should be -

    <form class="index-form" name="LoginForm">
       <div class="index-input">
         <button onclick="myFunction(); return false;">Login</button>
       </div>
   </form>
   <script>
      function myFunction(){
        window.location = "https://blahblah.com/auth/?client_id=fdsgsnlr";
      };
   </script>

In addition

<button> defaults to <button type="submit"> which submits the parent form, you can instead use <button type="button"> which does not submit the form.