How to disable all controls on the page using jQuery

Today, I got into a situation where for some reason I need to disable all the controls on the page on client side. So I have implemented it using jQuery and sharing the solution of the problem "how to disable all controls of the page using jQuery".

Below jQuery code will get called on click of button called "btnDisable" and set "disabled" attribute to all the controls on the page, which will in turn disable all the control including the button "btnDisable".

//Code Starts
$(document).ready(function() {
    $("#btnDisable").click(function(e) {
        $("*").attr("disabled", "disabled");
        e.preventDefault();
    });
});?
//Code Ends

But there is one problem with the code, that now there is no way or event to handle to enable the controls. To handle this, either 2 separate buttons can be used or the same button can be handle to enable and disable controls. To use same button for both operations, instead of click event use toggle event. "toggle" binds two or more handlers to the matched elements, to be executed on alternate clicks.

So with toggle, one need to specify 2 different event handlers. You can specify more than 2 event handlers as well. If more than two handlers are provided, .toggle() will cycle among all of them. For example, if there are three handlers, then the first handler will be called on the first click, the fourth click, the seventh click, and so on.

So in the first event handler,

  • First set disabled attribute to all the controls.
  • After remove the disabled attribute from the button.
  • And set text of button to "Enable".

And 2nd event handler,

  • First remove disabled attribute from all the controls.
  • And set text of button to "Disable".
//Code Starts
$(document).ready(function() {
    $("#btnDisable").toggle(function(){
        $("*").attr("disabled", "disabled");
        $(this).removeAttr("disabled");
        $(this).val("Enable");
    }, function(){
        $("*").removeAttr("disabled");
        $(this).val("Disable");
    });
});?
//Code Ends

Feel free to contact me for any help related to jQuery, I will gladly help you.



Responsive Menu
Add more content here...