Beework Web Design Logo

  Search

  

Skype: beeworkweb
Email:info@beework.net

Sales (free):
0800 882 4173

Support:
0870 978 0583

Mobile:
07866 627185

Registered Member of the UK Web Design Association 
Registered Member
of the UK Web Design
Association

Valid XHTML 1.0 Strict



Generates The JavaScript Code for a For Loop Statement

Generates JavaScript for do loop code. Specify the number of times to create the loop and click Generate Code.

Number of Repeats
Copy and paste this code to the <HEAD> section of your page

for statement

A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. A for statement looks as follows:

for ([initial-expression]; [condition]; [increment-expression]) {
   
statements
}
When a for loop executes, the following occurs:

  1. The initializing expression initial-expression, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression of any degree of complexity.
  2. The condition expression is evaluated. If the value of condition is true, the loop statements execute. If the value of condition is false, the for loop terminates.
  3. The update expression increment-expression executes.
  4. The statements execute, and control returns to step 2.
Example. The following function contains a for statement that counts the number of selected options in a scrolling list (a Select object that allows multiple selections). The for statement declares the variable i and initializes it to zero. It checks that i is less than the number of options in the Select object, performs the succeeding if statement, and increments i by one after each pass through the loop.

<SCRIPT>
function howMany(selectObject) {
          var numberSelected=0
          for (var i=0; i < selectObject.options.length; i++) {
                    if (selectObject.options[i].selected==true)
                              numberSelected++
          }
          return numberSelected
}
</SCRIPT>
<FORM NAME="selectForm">
<P><B>Choose some music types, then click the button below:</B>
<BR><SELECT NAME="musicTypes" MULTIPLE>
<OPTION SELECTED> R&B
<OPTION> Jazz
<OPTION> Blues
<OPTION> New Age
<OPTION> Classical
<OPTION> Opera
</SELECT>
<P><INPUT TYPE="button" VALUE="How many are selected?"
onClick="alert ('Number of options selected: '
+ howMany(document.selectForm.musicTypes))">
</FORM>