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,
limit: 8,
limitMsg: "",
checkFirst: false
};
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.limit = config.limit;
this.checkedNum = 0;
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++) {
if(this.checkedNum > this.limit) {
return false;
}
this.collection()[i].isSelected(value);
if(value) {
this.checkedNum++;
} else {
this.checkedNum--;
}
}
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) {
if (event.shiftKey) {
var clicked = _.indexOf(this.collection(), data);
if (_.isNull(this.lastChecked())) {
return this.turnSelection(0, clicked, true);
} else {
var index = _.indexOf(this.collection(), this.lastChecked());
return...