Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Labelling Checkbox and Radio in knockout

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/

like image 796
Rups Avatar asked Dec 01 '12 14:12

Rups


2 Answers

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

like image 60
nemesv Avatar answered Oct 22 '22 16:10

nemesv


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.

like image 4
Jesper Jensen Avatar answered Oct 22 '22 16:10

Jesper Jensen