Multiple Conditions

The following example sends the value selected in the form to the checkOptions( ) function. The input element is a checkbox with three options. Whenever an option is checked, the "checked" property of the option is set to true. Hence, you can test for the value of this property:

document.form_name.checkbox_name[option_index].checked
will be true if the respective option is checked, and false if it is not.

The function contains three if expressions that tests which combinations of two values of 1, 2, and 3 are checked. It will return an alert with any group of two it finds. (What will happen when all three are selected?)

There's an additional condition that test for false values. Note: we are asking whether the condition is "not true". If the expression returns false, it is "not true" (i.e., Bingo!) and the expression evaluates to true.

If you don't select anything, it will do nothing.)


Example

Select none or at least 2 items:

1
2
3



The Function Code

<script language="JavaScript"> <!-- function checkOptions(values) { if (values[0].checked == true && values[1].checked == true) { alert("1 and 2 are selected."); } if (values[1].checked == true && values[2].checked == true) { alert("2 and 3 are selected."); } // the following statement is equivalent to the preceding two // "checked" is a property of checkboxes; it is either // true or false; // hence, the evaluation 'values[0].checked' returns // either true or false and is valid as such if (values[0].checked && values[2].checked) { alert("1 and 3 are selected."); } // this tests for false values if (!values[0].checked && !values[1].checked && !values[2].checked) { alert("You didn't select anything."); } } //--> </script>