Lakhae
Lakhae

Reputation: 1899

How to disable submit button after click?

I am trying to disable button after click by using following code but it is not working.

View

<button class="button button-text-only" onclick=" $('#MyForm').submit() ">Create </button>

js

//inside document.ready
$('#MyForm').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

TIA

Upvotes: 1

Views: 5688

Answers (3)

Gary
Gary

Reputation: 61

Use the following to disable the button ...

$('#MyForm').on('click', function () {
    $("#myButton").attr('disabled', 'disabled');
});

Then if you need to enable you can remove disabled as below...

$("#myButton").removeAttr('disabled');

Upvotes: 1

Pete
Pete

Reputation: 58422

I would change your button to the following code

<button id="button-id" class="button button-text-only">Create </button>

then bind the click event this way instead:

$('#button-id').on('click', function(e) {
    e.preventDefault(); //prevent the form from being submitted

    $(this).prop('disabled', true);

    //process form with ajax otherwise your page is just going to reload and the button won't be disabled anymore
    var form = $('#MyForm');
    $.ajax({
        url: form.get(0).action,
        type: form.get(0).method,
        data: form.serialize(),
        success: function (result) {
           //do finished stuff here
           alert('done');
        }
    });
});

Upvotes: 2

Arko Elsenaar
Arko Elsenaar

Reputation: 1729

FIDDLE DEMO

$('button').click(function() {
    $(this).prop('disabled', true);
});

Upvotes: 6

Related Questions