Disabling form fields with jQuery
I can't count the number of times I have dynamically disabled form fields with Javascript. One of the most common cases is disabling a button after it's form is submitted so that the user doesn't try to submit the form multiple times. I use jQuery almost exclusively for DOM manipulation, and I have written variations of the following code many times.
var button = $("#the-button"); $("#the-form").submit(function (event) { button.attr("disabled", "disabled"); // ... Maybe some other stuff too ... });
Judging by the amount
of people who
also write similar code snippets, I'm surprised John Resig and company
haven't already included a helper for this behavior. In fact, today, upon
realizing that I had written this code so many times, I actually assumed that
something like $("#the-button").disable()
must already exist and
I just hadn't crossed paths with it yet. But I was wrong, so I have written it
myself, and hopefully others will find this useful as well.
(function ($) { // Disable a form field. $.fn.disable = function () { return this.attr("disabled", "disabled"); }; // Enable it again. $.fn.enable = function () { return this.removeAttr("disabled"); }; }(jQuery));
So when we update our example, we end up with the following, but of
course $(selector).disable()
and $(selector).enable()
will work with all form elements, not
just buttons.
var button = $("#the-button"); $("#the-form").submit(function (event) { button.disable(); // ... and if we want to enable it again: button.enable(); });
Knock yourself out.