Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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");
}
});
share|improve this question

2 Answers 2

up vote 2 down vote accepted

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);
}());
share|improve this answer
    
Awesome! Thanks. – Mirko Pastorelli Aug 5 '14 at 7:44

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.

share|improve this answer
1  
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. – Schism Aug 5 '14 at 13:44
    
If you are going for performance, why not do $result[0].disabled = $max.val() != $min.val() ? – Pevara Aug 5 '14 at 17:35
1  
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() – David Harkness Aug 5 '14 at 18:17

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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