JavaScript Primers #21

By Joe Burns

http://www.htmlgoodies.com/primers/jsp/article.php/3478341/JavaScript-Primers-21.htm (Back to article)

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

Deconstructing the Script


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

On To JavaScript Primer #22