<html> <head> <title>Javascript Labs</title> </head> <body> <script> course_name = "Adaptive Web Technology"; string_name = "This is the"; str_to_display = string_name + " " + course_name + " course." ; document.write(str_to_display); </script> </body> </html>
Comparing variable values:
if (course_name=="Adaptive Web Technology") { document.write("Success"); } else { document.write("Failed"); }
Some operators are:
==
Equal to !=
Not equal to <
Less than >
Greater than <=
Less than or equals >=
Greater than or equals
When a confirm box is presented and the user clicks on OK the value returned is true. When the user clicks on CANCEL the value returned is false.
Consider the following:
if ( confirm("Do you agree with the terms and conditions of the agreement") ) { alert("You agree and can continue setup"); } else { alert("You disagreed, exiting setup"); }
The syntax of the if else structure would be:
Now let's take a look at some sample javascript showing the if else structure, which you might want to test. Here we assume a 24 hour time format.if (condition) { action... } else { action... }
if (time >= 1200) { alert ("It is after noon."); } else { alert ("It is morning."); }
We can also have nested if else structures, so that we can check for a variety of conditions in a nested fashion. Here's how:
Here's an example of nesting if else structures:if (condition1) { action1... } else if (condition2) { action2... } else if (condition3) { action3... } ... else { actionN... }
In the example above we would have a value stored in the variable 'gpa' which we would use in evaluating the various conditions of the if else structure.
if (gpa > 3.5) { alert ("You are a very good student."); } else if (gpa > 2.9) { alert ("You are a good student."); } else if (gpa > 2.5) { alert ("You have an OK GPA."); } else { alert ("You really need to put in more effort."); }
You can also use and, or, and not to check for multiple conditions in the if statements.