Go to: Aardvark download page.

JavaScript


Often we must let the script make decisions for us.

Let's say that we let the users enter their age in a form field. If the visitor is 0-70 years old he/she should be directed to www.adobe.com and if the user is older we want a redirect to www.yahoo.com

The "if-else" method will be perfect for this task! Here is the script:

<script type="text/javascript">
<!--
function ageTest(){
var age=parseInt(document.myForm.myField.value)
if (age<71){
document.location="http://www.adobe.com"
}else{
document.location="http://www.yahoo.com"
}
}
// -->
</script>

There is some new stuff in this script so I will explain it line by line.

Line 1-3 should be old news to you now.

Line 4 introduces two new things. Earlier we wrote to a text field, this time we get the value from the text field, and we store in the variable "age". All values extracted from forms are text strings, so we need to transform text into numbers. parseInt() (parse integer) will do that for us before the value is stored in the variable.

Line 5 is the test. If "age" is less than 71 the next line will execute. If the test doesn't return "true" the script moves on to the next statement (pair of curly brackets).

Line 6 is the redirect to the adobe.com page.

Line 7 If the person wasn't 70 years or younger the "else" statement will kick in and execute the next line.

Line 8 is the redirect for people of the age 70+ to yahoo.com

There is actually an easier way to write the test, but it only works when you have a maximum of two alternatives (you sometimes need many if statements!). The shorter version looks like this, but I will not go into details in this tutorial.

<script type="text/javascript">

<!--
function ageTest(){
var age=parseInt(document.myForm.myField.value)
age<71? document.location="http://www.adobe.com": document.location="http://www.yahoo.com"
}
// -->
</script>

  • Paste this script or the first one in the head section of your page.
  • Add a form to your page and call it "myForm".
  • Add a text field to the form and call it "myField"
  • Make a text link and in the link inspector URL box write javascript:ageTest()
  • Enter you age in the text field and hit the text link.


What do you think this script is doing?

<script type="text/javascript">
<!--
function ageTest(){
var name=document.myForm.myField.value
if (name=="Lars"){
document.location="http://www.adobe.com"
}
if(name=="Nate"){
document.location="http://www.mindpalette.com"
}else{
alert("The user name didn't pass the test!")
}
}
// -->
</script>

Note that "==" means "equal to" while "=" is used to assign a value to a variable!

Back to tutorial index <<