Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Knockout.js "select all" checkboxes

I've just started playing around with Knockout.js, and it seems really cool. What I have is a grid. This grid has a column with a checkbox at the top to "select all" of the elements, as well as deselect. Standard grid behavior.

Here's my code so far:

Javascript:

// Define a "banner" class
function banner(inventory, name, artType, artSize) {
    return {
        isSelected : ko.observable(false),
        inventory : ko.observable(inventory),
        name : ko.observable(name),
        artType : ko.observable(artType),
        artSize : ko.observable(artSize)

    };
}

var viewModel = {
    banners : ko.observableArray([new banner("network", "Banner #1"), new banner("oo", "Banner #2")]),
    addBanner : function() {
        this.banners.push(new banner("network", "Banner"));
    },
    selectAll : function() {
        this.banners.isSelected(true)
    }       

};

ko.applyBindings(viewModel);

I'm binding the "selectAll" event to the checkbox like this:

<th><input data-bind="click: selectAll" type="checkbox" /></th>

And for each individual banner I have in my list, their checkbox looks like this:

<td><input data-bind="checked: isSelected" type="checkbox" /></td>

For some reason my selectAll function isn't working correctly. I'm fairly new to this OO javascript programming paradigm, so I may be doing something blatantly wrong here.

Thanks!

like image 975
dmackerman Avatar asked May 11 '11 18:05

dmackerman


2 Answers

banners is an array in this case, so you would need to access each item in the array and update the individual isSelected properties.

Something like:

ko.utils.arrayForEach(this.banners(), function(banner) {
   banner.isSelected(true);
});
like image 91
RP Niemeyer Avatar answered Oct 11 '22 21:10

RP Niemeyer


There's a more functional response at the link below. It deselects the "select all" box when on of the other checkboxes are deselected:

knockout check/uncheck all combo box

like image 42
zshift Avatar answered Oct 11 '22 21:10

zshift