1

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

4
  • Could you make a JSFiddle? Commented May 22, 2014 at 14:08
  • 3
    I see a button not an input submit. You may want to change that. Commented May 22, 2014 at 14:09
  • If on submit reloads the page then is logical to loose attr disabled.. Commented May 22, 2014 at 14:10
  • @Spokey is correct. And also I think that your button is not inside the form because of your javascript code. So, the second argument of the selector may be wrong. Commented May 22, 2014 at 14:11

3 Answers 3

6

FIDDLE DEMO

$('button').click(function() {
    $(this).prop('disabled', true);
});
Sign up to request clarification or add additional context in comments.

3 Comments

you better use prop("disabled",true)
Thank you all for help. @Arko Elsenaar I tried your code but it is not working.
Pawal, you are right. I have modified my answer and set up a really simple demo so you can see it in action. You can use this in your code.
2

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');
        }
    });
});

1 Comment

This is the best solution also we can add some AJAX properties, nice!
1

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');

1 Comment

You should use .prop() instead of .attr() here. Try .prop('disabled', true) and .prop('disabled', false) instead...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.