4
\$\begingroup\$

I need to use the same code in different jQuery attributes. Is it possible to put this if in a external function and call it inside a change event? I would like avoid duplicating code.

$("#Max").change(function () {
var max = $("#Max").val();
var min = $("#Min").val();

if (max != min) {
    $("#Result").attr("disabled", "disabled");
}
else {
    $("#Result").removeAttr("disabled");
}
});

$("#Min").change(function () {
var max = $("#Max").val();
var min = $("#Min").val();

if (max != min) {
    $("#Result").attr("disabled", "disabled");
}
else {
    $("#Result").removeAttr("disabled");
}
});
\$\endgroup\$
3
\$\begingroup\$

Yes, you can either assign the function to a variable or name it. You can further clean it up (slightly) by storing the jQuery selectors. Finally, I've wrapped it all up in an IIFE to avoid polluting the global space.

(function () {
    var $max = $("#Max"),
        $min = $("#Min"),
        $result = $("#Result"),
        changeHandler = function () {
            var max = $max.val(),
                min = $min.val();

            if (max != min) {
                $result.attr("disabled", "disabled");
            }
            else {
                $result.removeAttr("disabled");
            }
        };

    $max.change(changeHandler);
    $min.change(changeHandler);
}());
\$\endgroup\$
0
7
\$\begingroup\$

I think that @david-harkness code could be simplified further:

(function () {
    var $max = $("#Max"),
        $min = $("#Min"),
        $result = $("#Result"),
        changeHandler = function () {
            $result.prop("disabled", $max.val() != $min.val());
        };

    $max.change(changeHandler);
    $min.change(changeHandler);
}());

but I'm not really sure about the side effects of using prop instead of attr.

\$\endgroup\$
3
  • 1
    \$\begingroup\$ In the case of disabled, .prop() is actually preferred. You'll want to be keen on the differences of .prop() and .attr() when dealing with stuff like src, href, and other things that are parsed by the browser instead of left as-is. \$\endgroup\$ – Schism Aug 5 '14 at 13:44
  • \$\begingroup\$ If you are going for performance, why not do $result[0].disabled = $max.val() != $min.val() ? \$\endgroup\$ – Pevara Aug 5 '14 at 17:35
  • 1
    \$\begingroup\$ Wow, I had no idea about the distinction between attributes and properties. I highly recommend this SO thread and "Attributes vs. Properties" on jQuery.prop() \$\endgroup\$ – David Harkness Aug 5 '14 at 18:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.