<foreach>

Implemented according to the VoiceXML 2.1 specification.

Iterates through an ECMAScript array and executes the content contained within the <foreach> element for each item in the array. The <foreach> element may appear within executable content elements, or within <prompt> elements.

  • When it appears within executable content, <foreach> may contain any executable content elements.
  • When it appears within a <prompt>, it may contain only those elements valid within <enumerate> (that is, the same elements allowed within <prompt> except for <meta>, <metadata>, and <lexicon>).

Attributes

This section describes the attributes you can set for this element.

Name

Data type

Default

array

CDATA

required

item

CDATA

required

array

The array attribute specifies an ECMAScript that must evaluate to an array; otherwise, an error.semantic event is thrown.

item

The item attribute specifies the variable to store each array item upon iteration of the loop. A new variable will be declared if it is not already defined with the parent’s scope.

Both array and item must be specified, or an error.badfetch event is thrown.

Children

Note: The Child elements permitted for <foreach> depend on whether it appears within the <prompt> element. See the description above.

Parents

Example 1

In prompts, <foreach> inherits attributes such as bargein, bargeintype, count, timeput, xml:lang, xml:base from the parent <prompt>. However, the value of <cond> is always TRUE inside the <foreach> prompt.

Below, the <cond> is TRUE for <audio> (which appears inside the <foreach> prompt) regardless of <cond> in the parent prompt:

<vxml version="2.1">
  <var name="lang" expr="'en-US'"/>
  <var name="testCond" expr="false"/>
  <script>
    var aFruit = new Array(4);
    aFruit[0] = 'apple';
    aFruit[1] = 'orange';
    aFruit[2] = 'banana';
    aFruit[3] = 'strawberry';
  </script>
  <form>
    <block>
      <prompt> We will play list of available fruits </prompt>
      <prompt cond="if (!testCond) testCond = ((true)); else false" count="3">
        <foreach item="fruit" array="aFruit">
          <audio> <value expr="fruit"/></audio>
        </foreach>
      </prompt>
    </block>
  </form>
</vxml>

Example 2

<form id="pick_movie">
<var name="prompts" expr="GetMovieList()"/>
    <field name="movie">
        <grammar type="application/srgs+xml" src="movie_names.grxml"/>
        <prompt>Say the name of the movie you want.</prompt>
        <foreach item="thePrompt" array="prompts">
            <audio expr="thePrompt.audio">
                <value expr="thePrompt.tts"/></audio>
            <break time="300ms"/>
        </foreach>
        </prompt>
    </field>
</form>