6

I came across this strange code in a website I'm working on and don't understand how or why the behavior I'm seeing is happening.

<input type="submit" value="Save" onclick="document.location.href='http://www.google.com'" />

(Changed the href; it was actually pointing to the same URL as the form's action).

Because the onclick event fires before the form is submitted, I would expect this code to redirect the page to Google.com, and thus stop executing the page and never submit the form. Or possibly redirect to Google.com but then still finish submitting the form.

But what happens seems to be that the redirect is just completely ignored, and the form gets submitted anyway. Why would this happen?
I confirmed that the onclick event fires just fine; I moved the redirect into a function and called the function in onclick. The function was called just fine before the submit, but the redirect seemed to be ignored.

4
  • 1
  • I know that return false would prevent the submission, and in that case the redirect does happen. But why does the redirect not happen in this case? What's stopping it?
    – GendoIkari
    Aug 16, 2013 at 22:15
  • Can you re-produce this in a jsfiddle and also tell us which browser you're testing with?
    – Mario S
    Aug 23, 2013 at 22:39
  • I had the same problem recently. You could use <button>...</button> instead and attach a someform.submit() at the end of the button's action-eventcode. Alternatively, you may override the onsubmit form-attribute or respective submit-eventhandler. Aug 25, 2013 at 16:18

4 Answers 4

5
+50

I've just tested this behavior in different browsers, all browsers gave same results, here's my conclusion:

<!-- submit button inside form -->
<form method="post">
    <input type="submit" value="submit" /> <!-- onclick = submitted to same page -->
    <input type="submit" value="submitNredirect" onclick="document.location.href='http://www.google.com';" /> <!-- onclick = submitted to same page, ignored redirect -->
</form>
<!-- submit button without form -->
<input type="submit" value="submit" /> <!-- onclick = no submit or redirect occur -->
<input type="submit" value="submitNredirect" onclick="document.location.href='http://www.google.com';" /> <!-- onclick = redirect -->

As you know, javascript is linear, it executes the line of code that comes first. Let's say we have this form:

<form id="myform" method="post" onsubmit="alert('onsubmit');">
    <input id="mybtn" type="submit" value="submit" onclick="alert('onclick');" />
</form>
<script>
    $(document).ready(function() {
        $('#mybtn').bind('click', function() {
            alert('bind click');
        });
        $('#myform').bind('submit', function() {
            alert('bind submit');
        });
        // onclick > bind click > onsubmit > bind submit
    });
</script>

On clicking the button, the events bound to the button occurs first (the "click" events), then the events bound to the form occurs next (the "submit" events). The result is as follow:

  1. alert: onclick
  2. alert: bind click
  3. alert: onsubmit
  4. alert: bind submit
  5. form submission

If you include any redirect code in any of the functions, redirect will be ignored and submission occurs, I believe javascript overwrites the document.location.href with the form post process, the "form submission" is like an implicit/hidden line of code at the end of the script, if you don't return false; at some point, this implicit/hidden line is executed.

I'm not an expert, but that's what I understood after some testing. Please correct me if I'm wrong.

EDIT: What if we include a document.location.href in each function? like this:

<form id="myform" method="post" onsubmit="document.location.href='http://www.onsumbit.com';">
    <input id="mybtn" type="submit" value="submit" onclick="document.location.href='http://www.onclick.com';" />
</form>
<script>
    $(document).ready(function() {
        $('#mybtn').bind('click', function() {
            document.location.href='http://www.bindclick.com';
            return false;
        });
        $('#myform').bind('submit', function() {
            document.location.href='http://www.bindsumbit.com';
        });
    });
</script>

The state of the string value of "href" changes as follows (but executes the redirect at the end of script):

  1. document.location.href = 'http://www.onclick.com';
  2. document.location.href = 'http://www.bindclick.com';
  3. document.location.href = 'http://www.onsubmit.com';
  4. document.location.href = 'http://www.bindsubmit.com';
  5. document.location.href = '/'; // form submission
  6. javascript, do redirect based on "href" string value

but we have return false; after #2, which means will do redirect for "http://www.bindclick.com"

5
  • @LoSauer I know, I'm only using jQuery for testing, since the question is not about codes, it's about how javascript behaves
    – evilReiko
    Aug 25, 2013 at 10:42
  • I understand. But this has little to do with JavaScript or its "linearity". It is about how the handlers and thus the event-bubbling for the input[type=submit] are setup in a particular browser implementation. One option is overriding these handlers... Aug 25, 2013 at 10:49
  • @LoSauer I will say if the submit is the only question please refer this link echoecho.com/htmlforms12.htm this explains much more.. input[type=submit] is the jQuery/javaScript code that binds event to any input tag which is of type submit. you can ignore that steps then also the behaviour will be in the same sequence after removal of jQuery. I hope this will make things clear :)
    – MarmiK
    Aug 28, 2013 at 4:56
  • @MarmiK , @evilReiko . Several points that are flawed with the post: *) using a wrapper library to investigate specific browser-behavior is flawed. *) setting document.location.href to make a point is severly flawed, unless you set the anchor. *) The WHY isn't answered, but only event-hierarchy is listed Aug 29, 2013 at 15:59
  • If I'm reading this correctly, it sounds like this answers the "why" question pretty clearly, actually. Because setting document.location.href doesn't actually do an immediate redirect; rather it causes Javascript to redirect only after it's done processing the page. In fact, I just tested this by putting an alert before and after a redirect. I got both alerts, then it redirected. This seems to confirm what the answer says. Thanks!
    – GendoIkari
    Aug 30, 2013 at 13:50
0
<form action="http://www.yahoo.com" method="get">
<input type="submit" value="Save" onclick="document.location.href='http://www.google.com'" />
</form>

Click the Save button and I found depending on the browser you'll be directed to Yahoo (Chrome) unless you add return false to the onclick event. On IE 10 you get directed to Google.

I think someone who coded the browsers will have to answer this one.

0

I think this is a debatable question,

I will answer in term of behavior,

The default method of form is GET so on press of submit button form will get the data. Source Old Post

But if you have e.preventDefault() included with the document.location.href="http://www.google.com"

Now, if the link is a index.html the local index page will be called with respect to the website address, as you have removed the original link, its not possible to judge the why originally these was used!!!???

I can say in your question run this code,

<form onsubmit="javascript:alert('Form Submit called '+ this.method);">
    <input type=submit value=Submit onclick="javascript:document.location.href='http://www.google.com';alert('Button Submit');" />
</form>

this will clear the call of flow. as the document.location.href is never changed using this..

use this code after changing the href alert(document.location.href); this will give you the location which is not changed.

Perhaps prevent Default behavior may change this, but that is not part of your code..

I hope this will make things more clear.

0

What you are observing is the default and inherited behavior of the handlers for the HTMLInputElement's, unless overridden.

Solution:

Use the HTML5 button type-submit Element instead, which all modern Browsers should be able to handle correctly.

<form action="/" method="post" onsubmit="alert('submit event')">
  <input type="text" name="someinput" value="100">
  <button type="submit" onclick="alert('button onclick handled before form-submit')">submit</button>
</form>

Explanation:

You did not provide a specific browser, but perhaps you are using WebKit, which had a problem with the onsubmit / onclick event hierarchy before.

On the project's code-site you can search for the code that implements the various HTMLElement's.
For instance a search for onsubmit will lead to an Webkit onsubmit-event bubbling test.

One option to workaround this issue of event-bubbling, is to use a button and rendering it into a "submit", by finding its enclosing form and submitting it through the function (HTMLFormElement-instance).submit().

Another is by changing the submit handler of the form, which should be what you are looking for.

<form action="/" method="post" accept-charset="utf-8" id="myform3"
   onsubmit="event.stopPropagation(); event.cancelBubble = true;">
   A form with the default Browser submit-handler overwritten:
   <br>
   <input type="text" name="someinput" value="100">
   <input type="submit" name="commit" value="Submit" 
     onclick="alert('will alert first and submit later  using the browser default submit handler.');">
 </form>

All cases are demonstrated in this fiddle.

Cheers!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.