The if
construct is a control statement. It controls the program flow based on a logical expression that evaluates either to true
or false
.
The structure of an if
statement is as follows:
if (expression) { statement; }
The statement is executed only if the expression evaluates to true
.
The following example sends the value selected in the form to the checkOptions( )
function. The function contains three if
statements that check whether the passed value is 1, 2, or 3, respectively. If the condition evaluates to true
, it enters the statement block and executes the enclosed print statement.
<form action="javascript:;" method="post" id="form1"> <select name="selectGroup"> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> </select> <br /><br /> <input type="button" name="button1" value="Submit" onclick="checkOptions(selectGroup[selectGroup.selectedIndex].value)"> </form>
<script type="text/javascript"> <!-- function checkOptions(selectedValue) { document.write("<p>Checking option 1"); if (selectedValue == 1) { document.write("<p>1 = 1\nFound match."); } document.write("<p>Checking option 2"); if (selectedValue == 2) { document.write("<p>2 = 2\nFound match."); } document.write("<p>Checking option 3"); if (selectedValue == 3) { document.write("<p>3 = 3\nFound match."); } document.close(); } //--> </script>