Student
Student

Reputation: 1863

How to disable/readonly form while processing/submiting?

I am using AJAX to submit forms. I am using following code to submit a form via AJAX.

jQuery('form.AjaxForm').submit( function() {        
        $.ajax({
            url     : $(this).attr('action'),
            type    : $(this).attr('method'),
            dataType: 'json',
            data    : $(this).serialize(),
            success : function( data ) {
                        for(var id in data) {   
                          jQuery('#' + id).html( data[id] );                                
                        }
                      }
        });
        return false;
    });

Question:

I want to disable/readonly while server is processing form data after submit. Form should be normal after submit or any error. Some times user press submit button more than one time and we get unwanted duplicates entries in database.

Any idea ?

Thanks

Upvotes: 0

Views: 2037

Answers (3)

Will
Will

Reputation: 20235

function disable() {
    return false;
}

// Disable form
jQuery('form.AjaxForm').bind( "submit", disable );

// Enable form
jQuery('form.AjaxForm').unbind( "submit", disable );

Or if you want to prevent inputs from being modified:

// Disable
jQuery('form.AjaxForm input').each( function() {
    jQuery( this ).attr( "disabled", "disabled" );
});

// Enable
jQuery('form.AjaxForm input').each( function() {
    jQuery( this ).attr( "disabled", "" );
});

Upvotes: 1

Eric
Eric

Reputation: 1374

Disable the submit button before the $.ajax call in your submit handler:

$('#yoursubmit').attr('disabled', 'disabled');

And enable it again in the $.ajax call's success/error handlers:

$('#yoursubmit').attr('disabled', '');

Upvotes: 1

Ellery Familia
Ellery Familia

Reputation: 539

This will disable submit button once it's clicked.

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

Upvotes: 1

Related Questions