Range check - onchange
Check range of checkboxes in knockout.js via onchange
by keddie
HTML
<script src="//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th colspan="2">Control</th>
<th>Values</th>
<th>Name</th>
</tr>
</thead>
<tbody data-bind="foreach: values">
<tr>
<td>
<input type="checkbox" data-bind="checked: $data.isSelected"></input>
</td>
<td>
<input type="checkbox" data-bind="click: $root.checkboxesModel.handleSelectionEvent, attr: { checked: $data.isSelected }"></input>
</td>
<td data-bind="text: $data.isSelected">a</td>
<td data-bind="text: $data.name"></td>
</tr>
</tbody>
</table>
JavaScript
var GeneralModel = function() {
this.values = [
{ isSelected: ko.observable(false), name: "a" },
{ isSelected: ko.observable(false), name: "b" },
{ isSelected: ko.observable(false), name: "c" },
{ isSelected: ko.observable(false), name: "d" },
{ isSelected: ko.observable(false), name: "e" },
{ isSelected: ko.observable(false), name: "f" }
];
var config = {
collection: this.values,
};
this.checkboxesModel = new CheckboxesModel(config);
}
/**
* Checkboxes model for range, exlusive etc. selection
* @param {array} config
*/
var CheckboxesModel = function (config) {
this.collection = ko.observable( config.collection );
this.lastChecked = ko.observable(null);
this.turnSelection = function(index1, index2, value) {
var start = index1 < index2 ? index1 : index2;
var end = index1 < index2 ? index2 : index1;
for(var i = start; i <= end; i++) {
this.collection()[i].isSelected(value);
}
return true;
}.bind(this);
this.turnOffAll = function() {
this.turnSelection(0,this.collection().length-1, false);
}.bind(this);
this.turnOnAll = function() {
this.turnSelection(0,this.collection().length-1, true);
}.bind(this);
this.handleSelectionEvent = function (data, event) {
this.turnOffAll();
data.isSelected(!data.isSelected());
return true;
}.bind(this);
};
var viewModel = new GeneralModel();
ko.applyBindings(viewModel);