Wednesday, January 11, 2012

Disable submit button after user click using jQuery

Recently i have got a requirement to disable  the submit buttons Once it is clicked so that user should not click more than once.

 
                $("input[type='submit']").each(function () {
                    
                        $(this).attr("disabled", "disabled");
                });

Writing above code in button click you can disable all the submit buttons once user click any submit button in the form.  But some browsers  you cannot submit a form if you disable the button on  click event.

Here is the solution which works all the browsers  :



//Disable all the submit buttons when user click on any submit button
function DisableSubmitButtons( clickedButton) {
    $("input[type='submit']").each(function () {
        if (this.name != clickedButton)
            $(this).attr("disabled", "disabled");
        else {
         //hiding the actually clicked button
            $(this).hide();
            //Creating dummy button to same like clicked button
            $(this).after('<input type="button" disabled="disabled" value="' + $(this).val() + '" class="' + $(this).attr('class') + '" />');
        }
    });
}

This code disables all the submit buttons and hide the clicked button and put a new disabled button in it's place.


You can call this function with passing the clicked button Id


Example :Here is the example snipped code to call DisableSubmitButton function in Save button click



$('#btnSave').click(function(){
//I have hard coded to easily understand you can pass dynamically
  DisableSubmitButtons("btnSave");
});