Disabling a submit button after one click

GregM picture GregM · Feb 21, 2012 · Viewed 60.9k times · Source

Here's my code :

<form name='frm' id='frm' action='load.asp' method='post' onSubmit='return OnSubmit(this)' style='margin-top:15px'>
    <input type='submit' name='send' id='send' onclick="this.disabled=true;return true;" value='Send' title='test'>
</form>

I want my onsubmit function to be executed and I want the page to be submited. In my website, no submit and no function

I've tried to duplicate it here, but the form seems to be posted and my function never gets executed ... http://jsfiddle.net/V7B3T/1/

And I don't know when I should reactivate the button.

Should I do it in the document.ready, or in the onSubmit function ?

So if someone can fixed the fiddle :) and after that I'll compare it with my code. I think :S I'm lost

Thanks all

Answer

Bogdan picture Bogdan · Feb 21, 2012

If you want to validate the form or make any changes the before submitting and only submit if the form is valid you can do something like this:

<form id="frm" action="load.asp" method="post" enctype="multipart/form-data">
    <input type="submit" name="send" id="send" value="Send" title="test">
</form>

and the JavaScript code:

$('#frm').bind('submit', function (e) {
    var button = $('#send');

    // Disable the submit button while evaluating if the form should be submitted
    button.prop('disabled', true);

    var valid = true;    

    // Do stuff (validations, etc) here and set
    // "valid" to false if the validation fails

    if (!valid) { 
        // Prevent form from submitting if validation failed
        e.preventDefault();

        // Reactivate the button if the form was not submitted
        button.prop('disabled', false);
    }
});

Here's a working fiddle.