Reputation: 8177
So I have a label wrapping an input. I have a click event bound to the label, and another function bound to the input change. These need to be separate things that happen (there are other things that can change the value but I don't want the click handler firing for those).
The click triggers as expected, but the value never changes, much less fires the associated function.
vm.hasBeenClicked = ko.observable(false);
vm.currentValue = ko.observable('default');
vm.onLabelClick = function(){
vm.hasBeenClicked(true);
//fires no problem
}
vm.currentValue.subscribe(function(){
//this never fires
});
And the html:
<label data-bind="click: onLabelClick">
<input type="radio" data-bind="value: currentValue" />
</label>
Upvotes: 1
Views: 64
Reputation: 4304
First you'll want to use the "checked" binding with radios and checkboxes instead of "value". You also need to add return true;
to your onLabelClick function so that the label event doesn't conflict with the click event of the radio control itself.
var vm = {};
vm.hasBeenClicked = ko.observable(false);
vm.currentValue = ko.observable('default');
vm.onLabelClick = function(){
vm.hasBeenClicked(true);
//fires no problem
return true;
}
vm.currentValue.subscribe(function(){
console.log("updated");
});
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<label data-bind="click: onLabelClick">
option 1
<input type="radio" value='option 1' data-bind="checked: currentValue" />
</label>
<label data-bind="click: onLabelClick">
option 2
<input type="radio" value='option 2' data-bind="checked: currentValue" />
</label>
<br/>
clicked: <span data-bind="text: ko.toJSON(hasBeenClicked)"></span>
<br/>
value: <span data-bind="text: ko.toJSON(currentValue)"></span>
Upvotes: 1