Search code examples
javascriptjqueryfunctionvariableschaining

How to assign chained functions to a variable in jQuery


For example I want to assign a chained process into different variables and use them in different conditions.

var disable_btn = true;
var button_me = $('#contents.getsamplekit .sample-form .form #submit-btn-freeSample-me');
var button_disabled = button_me.attr("disabled",true).css("background","red"); // need to add more functions.
var button_enabled = button_me.removeAttr("disabled").css("background","green"); // need to add more functions here as well.
(disable_btn) ? button_disabled : button_enabled; 
]

Solution

  • You're calling the functions when you assign the variables, not when you test disable_btn. If you want to wait, you have to define a new functions:

    function button_disable(button) {
        button.attr("disabled", true).css("background", "red");
    }
    function button_enable(button) {
        button.removeAttr("disabled").css("background","green");
    }
    (disable_btn ? button_enable : button_disable)(button_me);