jQuery addClass example
Change class name on click in jQuery
by st3fan
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div id="page">
<p data-bind="{text:heading}"></p>
<ul data-bind="foreach: categories">
<li>
<!-- $root.selectedCategories -->
<input type="checkbox" data-bind="checkedValue: id, checked: $root.selectedCategories, attr: { id: 'category_' + id }">
<label data-bind="{ text:name, attr: { for: 'category_' + id } }"></span>
</li>
</ul>
<!--div id="checkboxList" class="checkbox-list" data-bind="template: { name: 'checkboxListItem-template', foreach: categories }">
</div-->
<pre data-bind="text: ko.toJSON($root)"></pre>
</div>
<!-- script type="text/html" id="checkboxListItem-template">
<div>
<label>
<input type="checkbox" data-bind="{value: id, checked: selected}" />
<span data-bind="{text: name}"></span>
</label>
</div>
</script -->
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
ul {
list-style: none;
padding: 0;
}
#page {
background: #fff;
padding: .5em;
}
pre {
display: block;
background: #000;
color: #fff;
white-space: pre-wrap;
padding: 5px;
width: 80%;
border-radius: 3px;
transition: all 0.5s;
}
button {
background: #0084ff;
border: none;
border-radius: 5px;
padding: 8px 14px;
font-size: 15px;
color: #fff;
}
#banner-message.alt {
background: #0084ff;
color: #fff;
margin-top: 40px;
width: 200px;
}
#banner-message.alt button {
background: #fff;
color: #000;
}
JavaScript
var categories = [
{ id: 1, name: "A", selected: true },
{ id: 2, name: "B", selected: false },
{ id: 3, name: "C", selected: false }
];
var selectedCategories = $.map(
$.grep(categories, function(item) { return item.selected; }),
function(item) { return item.id; });
var viewModel = {
heading: ko.observable("Tjeeena!"),
selectedCategories: ko.observableArray(selectedCategories),
categories: ko.observableArray(categories)
};
viewModel.selectedCategories
.subscribe(function(newValue) {
console.log(newValue);
});
console.log(viewModel);
$(function() {
ko.applyBindings(viewModel, $("#page")[0]);
});