6

If I have a button that sets off a jquery script is there a way to make sure the button is inactive until the script completes?

3 Answers 3

37

This is one area where I like to extend jQuery:

$.fn.disable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = true;
    });
}

$.fn.enable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined") this.disabled = false;
    });
}

and then you can do:

$("#button").disable();
$("#button").enable();

I find myself disabling/enabling controls a lot.

Sign up to request clarification or add additional context in comments.

1 Comment

I prefer this solution. You could easily enhance the function to change the text, too.
10

Somewhere at the beginning of your script (probably on the button's click event), set the button's disabled attribute to true:

$("#mybutton").attr("disabled", true);

Then, when complete, remove that attribute:

$("#mybutton").removeAttr("disabled");

EDIT:

If you want to get (slightly) fancy, change the text of the button while you're doing the work. If it's an image button, you can change the src to a friendly "please wait" message. Here's an example of the button text version:

$("#mybutton").click(function() {
  var origVal = $(this).attr("value");

  $(this).attr("value", "Please wait...");
  $(this).attr("disabled", true);

  //Do your processing.

  $(this).removeAttr("disabled");
  $(this).attr("value", origVal);
});

Comments

3

Thanks cletus for your function. I have used your function and created my own to toggle disabled elements.

$.fn.toggleDisable = function() {
    return this.each(function() {
        if (typeof this.disabled != "undefined"){
                if(this.disabled){
                    this.disabled = false;
                }else{
                    this.disabled = true;
                }
        }
    });
}

Comments

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.