Use these to jump around or read it all
The Concept
The Script
The Script’s Effect
Deconstructing the Script
What You’ve Learned
Your Assignment
![]()
The Concept
This example introduces you to the IF statement. Now we can decide what to do if a condition is true. This program asks the user if s/he likes sports. If the answer is “yes,” the program responds “I like sports, too.” If the answer is “no,” the program responds “I hate sports, too.” It’s a bit wishy-washy, but a nice, short introduction nonetheless.
Notice that if the user types in anything but “yes” or “no” the response is “Answer yes or no.” Pretty tricky, huh?
The IF statement is followed by a condition and what to do if it is true. TRUE can be one statement or many statements. The
program knows where the TRUE statements start and stop because they are contained in {brackets}.
The Script
<HTML>
<HEAD>
<SCRIPT type="text/javascript">
function askuser()
{
var answer=" "
var statement="Answer yes or no"
var answer=prompt("Do you like sports?")
if ( answer == "yes")
{statement="I like sports too!"}
if(answer == "no")
{statement="I hate sports too!"}
alert(statement)
}
</SCRIPT>
</HEAD>
<BODY>
<h1>Activities</h1>
<FORM action="">
<INPUT TYPE="button" VALUE="click me"
onClick="askuser()">
</FORM>
</BODY>
</HTML>
|
The Script’s Effect
function askuser()
{
var answer=” ”
var statement=”Answer yes or no”
var answer=prompt(“Do you like sports?”)
if ( answer == “yes”) {statement=”I like sports too!”}
if(answer == “no”) {statement=”I hate sports too!”}
alert(statement)
}
Deconstructing the Script
- Let’s start with the button:
<FORM action=""> <INPUT TYPE="button" VALUE="click me" onClick="askuser()"> </FORM>No surprises here, just a simple form button that triggers the askuser() function when the button is clicked.
- Here again is the function section of the script:
function askuser()
{
var answer=" "
var statement="Answer yes or no"
var answer=prompt("Do you like sports?")
if ( answer == "yes")
{statement="I like sports too!"}
if(answer == "no")
{statement="I hate sports too!"}
alert(statement)
}
- The prompt box asks for input.
- The input is looked at.
- If the answer is “yes” the statement “I like sports, too” is sent to the alert.
- If the answer is “no,” the statement “I hate sports, too” is sent to the alert.
- If the answer is neither, then you have an empty answer and the statement “Answer yes or no” is sent to the alert.
What You Have Learned
Your Assignment
Rewrite this program so that it asks the user if s/he is male or female. If the user types “male,” make the background blue. If the user types “female,” make the background pink. Remember, JavaScript is case-sensitive, so be careful of the case in the condition statement. For example:
if (anwer == “male”)If you type Male or MALE, the condition will be false!
Here’s the answer to this assignment
(this will open a new window)
The Concept
The Script
The Script’s Effect
Deconstructing the Script
What You’ve Learned
Your Assignment