I have a set of Checkboxes and a Select All checkbox implemented in the following way using Knockout. I need the "Select All" checkbox to be checked by default on page load.
$(document).ready(function(){
viewModel=new model(ko,$);
ko.applyBindings(viewModel);
});
function model(ko,$){
var jsonResponse= $.parseJSON(response);
this.factors=ko.observableArray(jsonResponse["factors"]);
this.selectedFactors=ko.observableArray();
this.selectAll = ko.dependentObservable({
read: function() {
return this.selectedFactors().length === this.factors().length;
},
write: function(newValue) {
this.selectedFactors(this.selectedFactors().length === this.factors().length ? [] : this.factors().slice(0));
},
owner: this
});
}
HTML:
<table>
<tr>
<td><input type="checkbox" id="selectAll" data-bind="checked: selectAll" />Select All</td>
</tr>
</table>
<table data-bind="foreach: factorsSplitJsonArray">
<tr data-bind="foreach: $data">
<td>
<!-- ko if: $data.hasOwnProperty("factorCode") -->
<input type="checkbox" class="jqFactors" id="jqFactors" data-bind="checkedValue: $data, checked: $root.selectedFactors" />
<span data-bind="text: factorDescription"></span>
<!-- /ko -->
</td>
</tr>
</table>
When I select or deselect any checkbox or the SelectAll checkbox the observableArray ie selectedFactors get changed. Now I need the "Select All" checkbox to be selected by default on page load and the selectedFactors should also have all the selected factors in it.
I am new to Knockout and unable to find out how to implement this using Knockout. What if we somehow call the function selectAll explicitly, will it do the job? How do I call a ko.dependentObservable function. Can some one please help me.
Aucun commentaire:
Enregistrer un commentaire