views:

242

answers:

3

Hi All,

I am having problem that when i am trying to submit the form by clicking on the submit button it takes some time to post request during this if i am again click on the Submit button it will again send the all parameters and parametrs get saved twice, thrice ....so on.

I don't know how to limit the the submit button so that form shouldn't get submitted twice. I think when i cliked on submit i have to disable submit button so that user can't click it again, is it right approach to doing this?

+12  A: 
<input type="submit" onclick="this.disabled = true" value="Save"/>
Zoidberg
nice solution. :)
Plynx
Wonderfullly direct.
T.J. Crowder
+3  A: 

I love the simplicity and directness of Zoidberg's answer.

But if you want to hook up that handler using code rather than markup (some people prefer to keep markup and code completely separated), here it is using Prototype:

document.observe('dom:loaded', pageLoad);
function pageLoad() {
    var btn;

    btn = $('idOfButton'); // Or using other ways to get the button reference
    btn.observe('click', disableOnClick);
}
function disableOnClick() {
    this.disabled = true;
}

or you could use anonymous functions (I'm not a fan of them):

document.observe('dom:loaded', function() {
    var btn;

    btn = $('idOfButton'); // Or using other ways to get the button reference
    btn.observe('click', function() {
        this.disabled = true;
    });
});

Doing it using jQuery will look very similar.

T.J. Crowder
Good answer, multiple options are always good, especially when they involve a solid library.
Zoidberg
+4  A: 

Disabling the button is one solution, but potentially poses a problem for keyboard users who just hit enter to submit a form. In this scenario, the button won't be disabled. The sure-fire method would be to handle the onsubmit event like so:

(function () {
    var allowSubmit = true;
    frm.onsubmit = function () {
       if (allowSubmit)
           allowSubmit = false;
       else 
           return false;
    }
})();

(well, as sure-fire as you can get with JS enabled anyway). You could disabled the button as a visual confirmation to the end user that the form can only be submit once too.

Andy E
True enough, I guess if someone can spastically hit the mouse, they can spastically hit the enter button too
Zoidberg
Very correct. It's also nice to show a message that the information is being sent (e.g., next to the submit button after it's been disabled).
Marcel Korpel