Thursday, May 2, 2013

Simple checkbox list using Knockout JS


Often we need to display list of checkboxes in HTML and there is no native HTML control for checkbox list.
If you are from ASP.Net background then you will know that there exists an asp control for checkbox list. However here we are not going to discuss that.
Here we will see how to generate a customizable checkbox list using Knockout.JS.

Setting up Knockout JS

First step is to setup Knockout.JS framework in your web based application. In respect of time, for that purpose let me redirect you to KnockoutJS. Here you will get steps required to wire knockout with your web application.

Knockout ViewModel

Let us say, you are having a list of fruits (Apple, Mango, Grapes, etc.) which you want to display in a checkbox list. Then you should have an KO observable array for that. You can achieve it simply by following similar code in you JS file:
Assumption : You are having your ViewModelReady with data coming from server.

var self = this;
self.fruitsList = ko.observable([]);
self.selectedFruits = ko.observable([]);

if (data.fruitsList != null) {
   self.fruitsList ($.map(data.fruitsList, function (item) { 
         return new SelectedListItemViewModel(item) }));

Separate helper function
Assumption : Object coming from server side is having "Value", "Text" and "IsSelected" properties.

function SelectedListItemViewModel(data) {
    this.Key = ko.observable(data.Value);
    this.Name = ko.observable(data.Text);
    this.IsSelected = ko.observable(data.IsSelected);

HTML code

In your HTML supported page you can keep the following HTML code to render the checkbox list:

We created a container
to hold all the checkboxes with some specified width and height so that it should get a look of list of controls.
For each item in the fruitList, one checkbox will get created and its value property will get binded with item's Key value.
To display text, we added a span and binded its text property with item's Name value.
Depending upon your object's properties, these two will vary from my example.

The important part to be noted here is another KO observable array "selectedFruits". On checking the checkbox, this observable will get filled with one item and will hold the "value" property of the checkbox. Using this observable array we can find out that in UI how many and what all checkboxes are selected.
Also if this list "selectedFruits" is already having some values in it which are same as of the checkbox's value property then the checkbox will appear as checked. Isn't it good for us!!!

Rest all depends on you that how you want to post this data to server back again.
Happy coding.

No comments: