Why Submitting A Form Overrides Setting Location.href In A Submit Button Click Handler? February 18, 2023 Post a Comment This question is inspired by this post. In a nutshell: Why window.location.href is not redirecting to a new page (example.com) when executing the code below? Solution 1: You can see easier here what is happening step by step if you will try tu change location drunning form submission JSFIDDLE If you will check your browser network tab than you can see that the submit request is cancelled (but still sent) by redirect request. I believe that same situation occurs when you trying to do it onclick or onsubmit the first request just cancelling the next one and prevent window.location.href redirection. Solution 2: I belive the key thing here is not to view the problem as 'form submission vs page redirect', but as an event-listeners issue. What you are doing is to attach an event listener to an html element. And it seems that the policy of DOM elements is to execute all the event listeners first, and then the event itself . In your case, the page is redirected to the url you provided, because you set window.location inside the listener, then the submit event itself takes place, so the same blank page is reloaded The fact that "event flow process will complete after all listeners have been triggered" is stated here: http://www.w3.org/TR/DOM-Level-2-Events/events.htmlBaca JugaHow Can I Refresh A Form Page After The Form Submits To _blank?Cannot Post Span Value By Document.form.submit'onmousedrag' Event Js So far I haven't figgured out a way to execute the listeners after the event , but if that can be done, that is all you need to make this example work Solution 3: The main issue is that there is nothing preventing the submit button from actually submitting the form. You would need a return false somewhere for that to happen. I'm not fully certain whether the Submit button logic or the click handler is happening first, but regardless, the form post is taking precedence. I was able to get the following to work: <html> <head> <script type="text/javascript"> function redirect() { window.location.href = "http://www.example.com"; return false; } </script> </head> <body> <form method="GET" action=""> <input type="submit" id="submitbtn" value="Submit" onclick="return redirect()" /> </form> </body> </html> Copy This example does remove the programmatic addition of the click event, but if that's a hard requirement it should be possible to add that back in. Share You may like these postsDetecting DOM Change EventsHow To Send PDF File To Frontend?Mousemove And Cross-browser E.whichRecursively Find Keys On An Object Post a Comment for "Why Submitting A Form Overrides Setting Location.href In A Submit Button Click Handler?"
Post a Comment for "Why Submitting A Form Overrides Setting Location.href In A Submit Button Click Handler?"