Skip to content Skip to sidebar Skip to footer

Why Submitting A Form Overrides Setting Location.href In A Submit Button Click Handler?

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.

enter image description here

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

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

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.

Post a Comment for "Why Submitting A Form Overrides Setting Location.href In A Submit Button Click Handler?"