Conditional logic
The actions you want the application to take may depend on certain conditions. VoiceXML supports three conditional logic elements that let you specify actions based on the evaluation of a conditional expression:
-
The <if> element executes a block of code if and only if the listed condition is satisfied. Each <if> element can optionally contain one or more <elseif> elements, and one <else> element.
-
Within an <if> element, <elseif> elements can be used to execute alternative blocks of code if all previous <if> or <elseif> conditions were not met, and the condition of the current <elseif> element is satisfied. You can include several <elseif> elements in the same <if> statement. Only the first <elseif/> element whose condition holds true is executed—any subsequent <elseif/> element is ignored, even if it is also true.
-
The <else/> element executes an alternative block of code if all previous conditions in the <if> element and <elseif/> elements failed.
By definition, an <else/> element must be the last part of the <if> element: you cannot have an <else/> followed by an <elseif/> statement.
An <elseif> or <else> element is always self-contained: that is, a slash always appears before the delimiter closing angle bracket (<elseif/>, <else/>). The instructions themselves follow the element.
The conditions in <if> and <elseif> elements are expressed as Boolean-valued ECMAScript expressions. For example, consider the <if> statement from the ConfirmDeliveryNow.vxml document in the PizzaTalk application. It appears after the caller is asked whether they would like an immediate delivery:
<if cond="confirm == 'yes'">
<assign name="DeliveryTime" expr="'now'"/>
<goto expr="'WrapUp.jsp?toppings=' + PizzaToppings"/>
<else/>
<goto next="GetDeliveryTime.vxml"/>
</if>
If the caller says yes, the application transitions to the WrapUp.jsp document. If the caller says no, the application instead transitions to a different document to find out what delivery time the caller would prefer.
Be careful to use a double equals sign (==) in a condition to indicate that it is a comparison. A single equals sign is a command to assign the value to the variable, and overwrites the actual value with the value specified in the condition.
As with any ECMAScript expression, the characters “<“, “>”, or “&”must be replaced with the corresponding escape sequence “<”, “>”, or “&”.