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");
}
});
2 Answers 2
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);
}());
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.
-
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 likesrc
,href
, and other things that are parsed by the browser instead of left as-is. \$\endgroup\$Schism– Schism2014年08月05日 13:44:30 +00:00Commented Aug 5, 2014 at 13:44 -
\$\begingroup\$ If you are going for performance, why not do
$result[0].disabled = $max.val() != $min.val()
? \$\endgroup\$Pevara– Pevara2014年08月05日 17:35:00 +00:00Commented Aug 5, 2014 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– David Harkness2014年08月05日 18:17:02 +00:00Commented Aug 5, 2014 at 18:17