patternjavascriptMinor
Avoiding code duplication for attribute-removal code
Viewed 0 times
removalduplicationforattributecodeavoiding
Problem
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");
}
});Solution
I think that @david-harkness code could be simplified further:
but I'm not really sure about the side effects of using prop instead of attr.
(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.
Code Snippets
(function () {
var $max = $("#Max"),
$min = $("#Min"),
$result = $("#Result"),
changeHandler = function () {
$result.prop("disabled", $max.val() != $min.val());
};
$max.change(changeHandler);
$min.change(changeHandler);
}());Context
StackExchange Code Review Q#59082, answer score: 7
Revisions (0)
No revisions yet.