Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Using $index in Knockout.js

4.20/5 (2 votes)
16 Jul 2014CPOL 29.4K   34  
Using $index in Knockout.js

Introduction

$index is the feature of the knockout.js to point current items index in array. But there are some differences in its uses. Here, let’s see how we can use it in both HTML DOM and inside view model itself.

Why Do We Need This $index

  1. To use items real index in HTML DOM.
  2. To show serial numbers of the item in HTML DOM, especially in data tables.
  3. Sometimes, we may have to get the index of the current item in view model itself too.

Using the Code

Here is the overall HTML DOM and view model code for the solution, JsFiddle.

HTML DOM:

HTML
<table>
    <thead>
        <tr>
            <td>Index</td>
            <td>Serail</td>
            <td>Item</td>
            <td>Show Index from inside Vm</td>
        </tr>
    </thead>
    <tbody data-bind="foreach: items">
        <tr>
            <!--item index in array-->
            <td data-bind="text: $index"></td>
            <!--item serial number from index-->
            <td data-bind="text: $index() + 1"></td>
            <td data-bind="text: $data"></td>
            <td><a href="#" data-bind="click: 
            $root.showItemIndex">Show</a></td>
        </tr>
    </tbody>
</table>

View Model:

JavaScript
function ViewModel() {
    var self = this;
    self.items = ko.observableArray([]);

    self.showItemIndex = function (item, event) {
        /*get current item index*/
        var context = ko.contextFor(event.target);
        var index = context.$index();
        alert('The item index: ' + index);
    };

    self.init = function() {
        var arr = ['CSE', 'EEE', 'IPE', 'BBA'];
        self.items([]);
        self.items(arr);
    };
}

$(document).ready(function () {
    var vm = new ViewModel();
    ko.applyBindings(vm);
    vm.init();
});

$index in DOM

HTML
<!--item index in array-->
<td data-bind="text: $index"></td>

Serial Number using $index in DOM

HTML
<!--item serial number from index-->
<td data-bind="text: $index() + 1"></td>

Item Index Inside the View Model

JavaScript
self.showItemIndex = function (item, event) {
    /*get current item index*/
    var context = ko.contextFor(event.target);
    var index = context.$index();
    alert('The item index: ' + index);
};

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)