The
Merry Monkey of
Multimedia Gulch Phone Book
This example is a
bit involved, so let's go through it
slowly. First let's look at
the
phone book itself. The phone book, which
is defined in the header (phone_book) and has seven entries,
looks like
this: |
var phone_book = new Array();
phone_book["happy"] = "(203) 555-1234";
phone_book["sleepy"] = "(203) 555-2345";
phone_book["sneezy"] = "(203) 555-4321";
phone_book["sleazy"] = "(203) 555-3245";
phone_book["sneery"] = "(203) 555-3213";
phone_book["bleary"] = "(203) 555-2365";
phone_book["tweaked"] = "(203) 555-1664";
The key
to each entry is
the
name of the dwarf, and the value of each entry is that dwarfs's
phone
number. When we want to get a phone number for our favorite dwarf,
say
"Sneezy," we write
this: |
var the_number = phone_book["sneezy"];
Now let's look at
the
form:
<form name="the_form">
<b>Name:</b>
<select onChange =
"displayNumber(phone_book,this.options[selectedIndex].value);">
<option value="happy">Happy
<option value="sleepy">Sleepy
<option value="sneezy">Sneezy
<option value="sleazy">Sleazy
<option value="sneary">Sneery
<option value="bleary">Bleary
<option value="tweaked">Tweaked
</select>
<p>
<b>Number</b>
<input type="text" name="number_box" value="">
</form>
Note that the form
and
the elements inside the form have names. This allows us to read and
write
to the form elements.
Also, take a look at the
onChange
handler in
the select tag. This says that when the
select is
changed, it calls the function displayNumber,
which is defined up
in the header. If I use the pulldown to select
"sneezy," the expression
this.options[selectedIndex].value returns
"sneezy." If you need
a refresher on this kind of form madness, check
out Part I, Day 5.
Once we've figured out what the user has selected, we
jump
to the displayNumber function, which looks
like
this: |
function displayNumber(phone_book, entry)
{
var the_number = phone_book[entry];
window.document.the_form.number_box.value = the_number;
}
It takes two parameters a phone book
and a
name to make this function work. The first line of
the
function,
var the_number = phone_book[entry];
looks the name up in the phone book,
and
the next line,
window.document.the_form.number_box.value = the_number;
puts that number into the form element
called
number_box.
And there you have it. As you can
see,
associative arrays are a good way to link one string to another. They're
useful for linking
names to
phone numbers, to passwords, to birthdays, and all kinds
of things.
A few lessons from now, I'll introduce another useful trick you
can do with
associative arrays, so don't cast them into the facts-best-forgotten pit
quite yet.
And now, if you're ready for it,
let's sink our teeth
into cookies!
next page»