I have html like this:
<div>
<input type="checkbox" id="checkbox", checked="checked"/>
<label for="checkbox">Copy values</label>
</div>
<div>
<input id="source" type="text"/>
</div>
<div>
<input id="target" type="text"/>
</div>
And I’m trying to implement jQuery code to copy value from source input to target one, only when the checkbox is checked. Here’s my code:
var checkbox = $("#checkbox");
var source = $("#source");
var target = $("#target");
var bindFunction = function () {
var copyValue = function () {console.log("asd");
target.val(source.val());
}
if (checkbox.is(":checked")) {
source.bind("keyup", copyValue);
}
else {
source.unbind("keyup", copyValue);
}
}
checkbox.bind("change", bindFunction);
bindFunction();
However, it does not work as expected – for some reason the copyValue function doesn’t get unbound. What am I doing wrong?
Here’s a jsFiddle.
You need to move the
copyValuefunction outside of thebindFunctionfunction.This is because it was creating a new instance of
copyValueeach time the checkbox was clicked so the unbind was running against a different function than the one that was originally bound.http://jsfiddle.net/5b93H/1/