foreach in knockout js and if condition in knockout js

foreach with if condition in knockout js

Hello everyone, I am going to share the code sample for how to use foreach loop and if condition in knockoutJs as given below.

Table of Contents

1. foreach loop in observable array knockout Js 
2. if in observable array knockout Js 
3. List in observable array knockout Js

This is for view code in Knockout Js for foreach loop and if conditions using knockoutjs MVC 4

<div data-bind="foreach: matters">
    <div data-bind="if: dateTime.length > 0">
                    <label data-bind="text: dateTime"></label>
<div class="time_data">
                <img src="~/Images/icon_status.png" /></td>
            <td data-bind="foreach: subMatter">
                <div data-bind="text: $data"></div>
                <div data-bind="text: hour"></div>
                <a href="#">
                    <img src="~/Images/icon_options.png" />

This is for viewModel code which use to display each row using foreach on matters collection [matters is a observable array]

<script type="text/javascript">
    $(document).ready(function () {
            url: "/MyTimeHome/GetMethod/",
            type: 'post',
            data: "{'matterId':'1' }",
            contentType: 'application/json',
            success: function (result) {
                // call to view model              
            error: function (jqXHR, textStatus, errorThrown) {
                var errorMessage = '';

        function getViewModel(result) {
            // Define a "matter" class.
            var matter = function (dateTime, hour, subMatter) {
                this.dateTime = dateTime;
                this.hour = hour;
                this.subMatter = ko.observableArray(subMatter);
            var viewModel = {
                matters: [],
                showRenderTimes: ko.observable(false)

            // push all data in view model
            for (var i = 0; i < result.length; i++) {
                var matterRow = new matter(result[i].createdOn + " | " + result[i].totalHours, result[i].totalHours,
                    [result[i].matterTitle, result[i].MyProperty1, result[i].matterComment]);

            // bind view model to knockout



Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - and
My Books - Interview Questions and Answers Books- Get Your Book in 15+ Digital Stores Worldwide..

You Might Also Like Powered by Blogger.
ASK Questions