Search code examples
jqueryshow-hidefunction-parameter

Passing jQuery.show() & jQuery.hide() as parameter to be applied on an element


As the title reads, I'd like to pass show() & hide() jQuery functions as parameters in another function.

function applyActionOnClass(attr, action) {
    $('#salesonhold_table tr').each(function () {
    if ($(this).attr('status') == attr)
        $(this).action;
    });
}

Here is when I call my applyActionOnClass function:

$(document).on('change', '.checkboxes', function () {
    var attr = $(this).val();
    if ($(this).is(':checked'))
        applyActionOnClass(attr, show());
    else
        applyActionOnClass(attr, hide());
});

To explain a bit the purpose of this, I have a table and each of its <tr> has a status attribute which differs them from each other. I have two checkboxes on top of the table, one for each possible status value and I'd like to hide/show corresponding <tr> when checkboxes are triggered.

The trigger and stuff work fine but when it comes to $(this).action; it says hide is not defined. Any idea what I did wrong there?

Thank you so much !


Solution

  • You can pass an anonymous function (or delegate) instead. This code handles that:

    function applyActionOnClass(attr, func) {
        $('#salesonhold_table tr').each(function () {
        if ($(this).attr('status') == attr)
            func($(this));
        });
    }
    

    This code passes the delegate in:

    $(document).on('change', '.checkboxes', function () {
        var attr = $(this).val();
        if ($(this).is(':checked'))
            applyActionOnClass(attr, function(e) { e.show(); });
        else
            applyActionOnClass(attr, function(e) { e.hide(); });
    });