Why Submitting A Form Overrides Setting Location.href In A Submit Button Click Handler? February 04, 2024 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 submissionJSFIDDLEIf 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 reloadedThe 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 JugaText Link Won't Submit Form By Javascript In Safari Using NameSubmit Form Using GreasemonkeyHow To Enable Submit Button Until Condition In A Multiple File Uploader?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 workSolution 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><scripttype="text/javascript">functionredirect() { window.location.href = "http://www.example.com"; returnfalse; } </script></head><body><formmethod="GET"action=""><inputtype="submit"id="submitbtn"value="Submit"onclick="return redirect()" /></form></body></html>CopyThis 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 postsCheck Atleast One Checkbox Is Checked On Form SubmissionPhp Form Submits Before Javascript ValidationHow To Enable Submit Button Until Condition In A Multiple File Uploader?Submit Form Using Greasemonkey 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?"