Wednesday, September 7, 2016

Disabling/Enabling events jQuery

The problem:
I'd been recently looking at how to disable/enable client button clicks using jquery in the context of manipulating rows in a result set. You can use classes to enable/disabled functionality but that leaves the buttons still able to be clicked.

The solution:
So after some investigating and help from a co-worker we found using the ".on" and ".off" jquery methods to disable and enable the functionality of the buttons when a list of results was in view. You don't want a user to be trying to do some kind of action on some portion of a result set while nothing is selected.

So here's the disable code:

$('#idOfElement').off('click');
$('#idOfElement').addClass('disabled');

Enable code:

$('#idOfElement').on("click", function () {
                EventFunctionDeclaredElseWhere();
            });
            $('#idOfElement').removeClass('disabled');

As a bonus this keeps your markup clean because you don't use the onclick="" to bind the event.

jQuery references:
http://api.jquery.com/off/
http://api.jquery.com/on/

This simple and effective way of handling events will work in general. I like the simplicity and separation of concerns.

No comments:

Post a Comment