In html, when we click on the text or hover over the text of a radio button or checkbox, we are able to select it with the html as shown below:
<label>
<input type="checkbox" />option 1
</label>
OR
<input id="checkboxid" type="checkbox" />
<label for="checkboxid">option 1</label>
I am trying to get the same behavior with knockout, but unable to find much help on the same:
<label data-bind="text: $data.optiontext">
<input type="checkbox" data-bind="value: $data.optionvalue, checked: $parent.selectedOptions" />
</label>
The View (or html) is below (Note the below code does not contain the above html, so when you try it you will need to make the above changes and check it):
<div data-bind="foreach: options">
<input type="checkbox" data-bind="value: $data.optionvalue, checked: $parent.selectedOptions" />
<label data-bind="text: $data.optiontext"></label>
</div>
<hr />
<div data-bind="text: selectedOptionsList"></div>
Here is the view model:
var viewModel = {
options: [
{ optiontext: 'Simple', optionvalue: "1" },
{ optiontext: 'Advanced', optionvalue: "2" }
],
selectedOptions: ko.observableArray(["2"])
};
viewModel.selectedOptionsList = ko.computed(function() {
return this.selectedOptions().join(",");
}, viewModel);
ko.applyBindings(viewModel);
Here is the jsFiddle link: http://jsfiddle.net/rupesh_kokal/AFzbY/
You can achieve the 1. version with using an extra span
for the text:
<label>
<input type="checkbox" data-bind="value: $data.optionvalue,
checked: $parent.selectedOptions" />
<span data-bind="text: $data.optiontext"/>
</label>
Demo fiddle.
Or the 2. version with using the attr binding to set the id
and the for
attribute:
<input type="checkbox" data-bind="value: $data.optionvalue,
checked: $parent.selectedOptions, attr: { id: optiontext}" />
<label data-bind="text: $data.optiontext, attr: {for: optiontext}" />
Demo fiddle
Yo can even get the binding to drop the extra span-element, by using Knockouts comment-binding syntax:
<label>
<input type="checkbox" data-bind="value: $data.optionvalue,
checked: $parent.selectedOptions" />
<!-- ko text: $data.optiontext --><!-- /ko --></label>
This will prevent the checkbox and the span from breaking up on two lines, if used in narrow spaces.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With