最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Onclick inside form element - Stack Overflow

programmeradmin0浏览0评论

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 = "/?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?

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./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?

Share Improve this question asked Nov 19, 2016 at 14:40 CharcoalGCharcoalG 3151 gold badge5 silver badges12 bronze badges 2
  • Return false from your onclick handler - onclick="myFunction(); return false;" – Vikas Sachdeva Commented Nov 19, 2016 at 14:45
  • Also see my edits to @VikasSachdeva answer – Victory Commented Nov 19, 2016 at 15:00
Add a ment  | 

2 Answers 2

Reset to default 7

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

Try this

<form class="index-form" name="LoginForm">
   <div class="index-input">
     <button onclick="myFunction()">Login</button>
   </div>
</form>

<script>
  function myFunction(e){
     e.preventDefault();
     window.location = "https://blahblah./auth/?client_id=fdsgsnlr";
  };
</script>
发布评论

评论列表(0)

  1. 暂无评论