How to select only one checkbox from a list of checkboxes in Knockout.js
I have a DOM structure of the following code:
<tr>
<td><label><input type="checkbox"></label></td>
</tr>
<tr>
<td><label><input type="checkbox"></label></td>
</tr>
... etc
Using knockout.js, when I select one checkbox, I want to highlight only the parent row with a background color. Right now, the code I was able to implement is selecting all the checkboxes and highlighting all the lines, as shown here in this script .
It is worth noting that the number of rows I have is dynamic and can be very large, so a scalable solution is required. I've already tried to understand the concept of observable arrays and I won't get very far.
How do I implement the above logic with Knockout? Thank you.
source to share
Take a look at this solution using the link observableArray
(of the script ):
- I created a constructor method
Checkbox
that creates checkboxes . - Note that each checkbox has an observable to determine when an item is selected .
- I also have
observableArray
one filled with checkbox objects. - Then I only need a
foreach
binding to display all the checkboxes that I have in the array. - Inside the bundle,
foreach
I added some bindings to show the shortcut, detect when checkbox is checkedand highlight if selected.
Html
<div data-bind="foreach: checkboxes">
<div data-bind="css: {'selected': isSelected}">
<label>
<input type="checkbox" data-bind="checked: isSelected"/>
<span data-bind="text: label"></span>
</label>
</div>
</div>
CSS
.selected {
background-color: yellow;
}
Js
var Checkbox = function(label){
this.isSelected = ko.observable(false);
this.label = label;
};
var checkboxes = [new Checkbox('Item 1'), new Checkbox('Item 2'), new Checkbox('Item 3')];
ko.applyBindings({
checkboxes: ko.observableArray(checkboxes)
})
It is so scalable that you just have to add new Checkbox()
in observableArray
.
source to share