knockoutJS foreach Bindings

In the last few articles, we covered most of the appearance and text bindings. In this article and the next few we shall study control flow bindings. Control flow bindings, as the name suggests control the flow of code execution. In this article we shall study knockoutJS foreach bindings.

KnockoutJS foreach bindings basically repeat html markup according to the number of elements in an array. In each markup repetition you can access the corresponding item in the array. Another very exciting prospect of foreach binding is that if you have an observable array, adding or removing elements from the array shall automatically reflect in the markup. Adding an element will add markup for the element and removing an element shall automatically remove markup.

Usually knockoutJS foreach bindings are used to display list of elements. Take a look at the following example where we simply display the names and ages of some random students in some imaginary school.

<!DOCTYPE html>
<html>
    
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
    
</head>

<body>
    
    <table>
        <thead>
            <tr><th>Student Name</th><th>Student Age</th></tr>
        </thead>
        <tbody data-bind="foreach: students">
            <tr>
                <td data-bind="text: studentName"></td>
                <td data-bind="text: studentAge"></td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        ko.applyBindings({
            students: [
                { studentName: 'Mark', studentAge: 21 },
                { studentName: 'Gren', studentAge: 19 },
                { studentName: 'John', studentAge: 23 },
                { studentName: 'Ygritte', studentAge: 18 },
                { studentName: 'Hodor', studentAge: 40 }
            ]
        });
    </script>
    
</body>
</html>

Download the code Try the code

Take a careful look at the above code. Check JavaScript view model section first. Here we declare an array named students. Each item in an array is an object written in JSON format. Each object has studentName and studentAge parameter. There are 5 objects in total.

Now come to the html view section. Here we have created a table to show the studentName and studentAge parameter from the objects in students array. Notice that the foreach binding is used with the “tbody” tag which means tha whatever is inside this tag shall be repeated the number of times the elements in the students array. Also, during each iteration the values for studentName and studentAge parameters shall be displayed within the

tags.

It is important to note here that if you remove or add more student objects in the students array in view model, the information of the newly added students will automatically be added into the table and vice versa.

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .