简体   繁体   中英

How can I run some JavaScript *after* a form submit event?

I'm working on an HTML form that may take a few seconds to submit. I'd like to disable some of the fields in the form after it's submitted.

I can do this in a handler on the form's submit event, but this fires before the form submits. If I disable the controls then, their values aren't included in the post data sent to the server.

I've tried cancelling the submit event in my handler, removing my submit event handler from the form, submitting the form myself via JavaScript, and then disabling the controls, but the problem there is that I need to know which button the user clicked on to submit the form. This information is in the original form submit, but obviously isn't in the one I trigger manually (as no button was clicked).

I could try to copy this information into my manual form submit, but is there a way to run my disabling code after the form submits?

Don't allow further submits by disabling the submit buttons, you don't need to do anything else. Alternatively, hide the form and replace it with something that spins so users are mesmerized into thinking that Something Important is happening.

After submiting the form you can trigger this function:

function name() {
    $("#target :input").attr("disabled", true);
    return true;
}

This code will disable all the from fields descended from the element with "target" as its id.

This version just matches all input elements:

function name() {
    $("#target input").attr("disabled", true);
    return true;
}

You have to include the jQuery library for this code to work.

This is pretty much the same as sp00m's answer, except it uses Javascripts native submit to prevent the recursive call.

$('#myForm').submit(function() {
    this.submit();
    disableFields(); // your own function
    return false;
});

You could use jQuery's .post() to submit, and .button().click() to detect what button was clicked

.post() takes a function to execute after the submission is complete

You could delay the execution of your operations so that they are called only after the submit has been made:

$('#myForm').submit(function() {
    setTimeout(function() {
        // Run disabling code here
    }, 1);
    return true;
}

setTimeout(fn, 1) will place the function inside at the end of the execution queue, so that the form submission has been started before the functions run.

setTimeout can be used for queuing operations a bit like thread indexing or z-index:

StackOverflow: Why is setTimeout(fn, 0) sometimes useful?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM