JSFiddle - React, Tailwind, and code Playground
by toddhd
HTML
<div data-bind="template: { name: 'locationTmpl', foreach: locations, templateOptions: { selections: selectedLocations } }">/</div>
<script id="locationTmpl" type="text/html">
<input type="checkbox" data-bind="attr: { value: $data }, checked: $data.isSelected" />
<span data-bind="text: $data.DisplayName"></span>
</script>
<hr />
<div data-bind="text: JSON.stringify(ko.toJS(selectedLocations), null, 2)"></div>
<hr />
<div data-bind="text: selectedLocationIds"></div>
JavaScript
function MyLocation(locationId, displayName, iSelected) {
this.LocationId = ko.observable(locationId);
this.DisplayName = ko.observable(displayName);
this.isSelected = ko.observable(iSelected);
}
var viewModel = function (items) {
this.locations = ko.observableArray([
new MyLocation('1','Starbucks1'),
new MyLocation('2','Starbucks2'),
new MyLocation('3','Starbucks3'),
new MyLocation('4','Starbucks4',true),
new MyLocation('5','Starbucks5')
]);
this.selectedLocationIds = ko.computed(function() {
var total = '';
ko.utils.arrayForEach(this.locations(), function(item) {
if(item.isSelected())
total += item.LocationId() + ' ';
});
return total;
},this);
this.selectedLocations = ko.computed(function() {
return ko.utils.arrayFilter(
this.locations(), function(item) {
return item.isSelected();
}
);
},this);
};
ko.applyBindings(new viewModel());