Javascript: For loop

Let’s step aside with form and look at for loop statement in Javascript.  We will apply for loop to radio button form in the next article.

In the example below, we have an array of 3 items.

To access the number of items, we can use item.length.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>For Loop</title>
    <script>
        function submitButton() {
            var item = ['one', 'two', 'three'];
            var i;
            var l = item.length;
            alert('No of item is ' + l);
            for (i = 0; i < l; i++) {
                alert(item[i]);
            }
        }
    </script>

</head>
<body>

<input type='button' value='Submit' onclick='submitButton()'>

</body>
</html>

button

Using for loop, it will cycle through the array and print out each item.

The above for statement starts by initializing i to 0. It checks that i is less than l, performs the alert statement, and increments i by 1 after each pass through the loop.

 

Series Navigation<< Javascript: Form with radio buttons
Javascript: Form with multiple radio buttons >>