Search code examples
phpjavascriptprototypejs

How to disable a form while the user is submitting it using Prototype?


When the user submits an HTML form, I want to disable the form while the server is processing it. I don't want the user to type any additional text, nor do I want them to rapidly tap the submit button to send multiple requests. I tried doing this with Prototype JS:

$('formId').observe(
    'submit',
    function(event) {
        Event.element(event).disable();
    }
);

The form correctly gets disabled, but on the server side, I error_log out $_POST and find that it is completely empty. This problem only occurs when the form is disabled upon submission.


Solution

  • If you disable the form, I think it will not submit / post your fields, because it'll be diabled, What I do in that cases is disable the submit button, not the whole form.

    $('formId').observe(
        'submit',
        function(event) {
            $$("input[type='submit']").each(function(v) {v.disabled = true;})
        }
    );
    

    Take a look to this How can I unobtrusively disable submit buttons with Javascript and Prototype?

    UPDATE:

    But disabling the submit button is not enough. People can hit the enter key on a text input to submit the form. Using the submit button is not the only way to submit a form

    Then you can make a combination with this answer https://stackoverflow.com/a/9693667/1078487

    var already_submitted = false;
    
    $('formId').observe(
        'submit',
        function(e) {
            // disable input
            $$("input[type='submit']").each(function(v) {v.disabled = true;})
            if ( already_submitted ) {
                new Event(e).stop();
                return false;
            } else {
                already_submitted = true;
            }
        }
    );