Now that you’ve mastered the basics of computer programming, it’s time to refocus on the Document Object Model (DOM). We’ve already seen that the DOM hierarchy starts with a Window object. Inside each Window object is a Document object. We’ll be spending this lesson going through the Document object and seeing how it can be used to get all kinds of information from your users and to dynamically present new information.
We’ve already had a good look at one of the properties of the Document object, the Images array. If you remember back to Lesson 4, the first image in a document can be modified by changing its src property. For example,
1 | window.document.images[0].src= 'some_new_picture.gif' ; |
will change the first image in a document to the GIF called some_new_picture.gif
. As you might have guessed, each Image in the Image array is itself an object in the DOM. That’s why images[0].src
works. It’s saying, get the Image object image[0]
from the Images array and set its src property. The whole statement above reads in English, “get the document property of this window, get the first image from the document’s image array, and change its source property to some_new_picture.gif
.”
The Image object has lots of other interesting properties. For example, you can have your JavaScript check to see if an image has been completely loaded before doing anything. However, these interesting properties will have to wait for later lessons. Gotta keep you coming back somehow, right? Today, we’ll be focusing entirely on forms and how to use them in JavaScript.
Forms are part of the HTML 1.0 specification. Many people don’t know about them, however, because there’s a misconception that they’re only useful if you (or someone you know) can do server-side CGI programming. As June points out in her
forms tutorial, forms can be fun even if you aren’t a CGI programmer. More important for this tutorial, JavaScript can be used to add all sorts of functionality to forms without the help of server-side CGI.
If you don’t know how forms work, check out
Jay’s tutorial and try writing some forms yourself. I’m going to assume that you know the basics.
The first thing you need to know about forms and JavaScript is that forms, like images, are stored in an array of objects. Just like you can refer to the first image on a page by calling it
window.document.images[0]
, you can refer to the first form on a page using
window.document.forms[0]
. Similarly, just like you can name images, you can name forms. For an example if
this form is written like this,
1 | <form name= "first_form" > |
3 | <input type= "text" name= "first_text" size= "40" |
5 | value= "Power to the primates!" > |
You can refer to the form in either of these two ways:
1 | var the_form = window.document.forms[0]; |
3 | var the_same_form = window.document.first_form; |
Although being able to refer to forms is sometimes useful, more often you want to refer to elements inside of forms, such as the text field in the last example. Here’s an example of manipulating the value of a text field.
Manipulating the Value of a Text Field
Click here and mouse over the links below the text field and see what happens.
This magic is performed by changing the value of the text field. The form looks like the one in the last example:
1 | <form name= "first_form" > |
3 | <input type= "text" name= "first_text" value= "Are you happy?" > |
The links that change the text field are:
1 | <a href= "#" onMouseOver="window.document.first_form.first_text.value= |
3 | 'Clap clap!' ;">Yes, and I know it.</a> |
5 | <a href= "#" onMouseOver="window.document.first_form.first_text.value= |
These are normal mouseovers; the important part is:window.document.first_form.first_text.value='Clap clap!'
. This says, “find the form called first_form
in the document, find the form element called first_text
, and set its value to ‘Clap clap!’.” The second line works similarly. This is very much like changing the src of an image. Instead of having a src, text fields have values.
Other types of form elements can be affected by messing with their values – for example, textareas:
The forms and links here are very similar to those above. The form is:
03 | <textarea name= "the_textarea" rows=10 cols=60> |
05 | Mouse over below to see the first verse of |
07 | The Webmonkey song, adapted from |
09 | "I Wanna Be Like You" (The Monkey Song) |
11 | from Walt Disney's <cite>The Jungle Book</cite> |
13 | written by Richard M. Sherman and Robert B. Sherman |
Notice that the form has a name, form_two
, and the textarea has a name as well, the_textarea
.
The links are basically the same as what you saw in the text field example:
1 | <a href= "#" onMouseOver="window.document.form_two.the_textarea.value= |
5 | <a href= "#" onMouseOver="window.document.form_two.the_textarea.value= |
7 | second_part;">Part 2</a> |
The only difference is that instead of assigning a string to the value of the textareas, I assigned variables that I defined in the header. View Source to see that they’re there. I only did this for the sake of neatness, to get those long strings out of the HTML. A well-groomed monkey is a happy monkey. Here’s one of the strings:
1 | var first_part = "Now I'm the king of the swingersnOh, the jungle VIPnI've reached the top and had to stopnAnd that's what botherin' me" ; |
Notice the "n"
. This is standard computerese for new lines. In general, because you’re working with HTML, the new line isn’t important. But if you’re writing something in a <pre>
tag, or you’re writing into a textarea, the "n"
comes in handy.
In addition to changing the values of form elements, JavaScript allows you to detect events that go on inside of them. Here’s an example of detecting events inside a text field.
Text Field Events
Text fields understand onBlur
, onFocus
, and onChange
. The onFocus
event occurs when someone clicks inside a text field. onBlur
happens when somebody moves out of a text field by clicking outside of it, or hitting “tab.” onChange
happens when somebody changes what’s in the text field and then moves outside the text field.
Try doing these things in the text field and see what happens in the textarea below it.
Here’s how this works. The text field looks like this:
1 | <input type= "text" name= "first_text" |
3 | onFocus= "writeIt('focus');" |
5 | onBlur= "writeIt('blur');" |
7 | onChange= "writeIt('change');" > |
Each of the event handlers calls the function writeIt()
, which I’ve defined in the header. The header looks like this:
03 | <title>Text Field Events</title> |
05 | <script language= "JavaScript" > |
09 | function writeIt(the_word) |
13 | var word_with_return = the_word + "n" ; |
15 | window.document.first_form.the_textarea.value += |
This should all look pretty familiar to you. The first few lines are the typical JavaScript preamble and the function definition. The first line in the body of the function …
1 | var word_with_return = the_word + "n" ; |
…. initializes a new variable, word_with_return
, and sets it equal to the string that was passed into the function concatenated with a "n"
. (Remember, the "n"
is standard computerese for “new line.”)
The next line …
1 | window.document.first_form.the_textarea.value += word_with_return; |
…. says, “set the value of the textarea to its current value plus the new variable.” This shortcut was covered when we learned about loops. It’s the same as saying:window.document.first_form.the_textarea.value =
1 | window.document.first_form.the_textarea.value + word_with_return; |
3 | It just takes less time. So far, we've seen a property of text fields and textareas (the value) and some events that they can handle. The remaining thing to know about these elements is the methods that they can handle:<code>blur()</code>, <code>focus()</code>, and <code>select()</code>. |
Here are some links to show you how focus()
and select()
work. Beware that they sometimes stop working after the first time:
Here are the form and the two links:
1 | <form name= "method_form" > |
3 | <input type= "text" name= "method_text" size=40 value= "Hey, hey, we're the monkeys" > |
5 | </form> <a href= "#" onMouseOver= "window.document.method_form.method_text.focus();" >Mouseover to focus</a> |
7 | <a href= "#" onMouseOver= "window.document.method_form.method_text.select();" >Mouseover to select</a> |
Accessing the methods of a text field is just like accessing the methods of any object:object_name.method()
. The name of a text field is window.document.form_name.text_field_name
. So, to call the focus()
method on the text field above, we call:
1 | window.document.method_form.method_text.focus(); |
That’s pretty much all there is to know about text fields and textareas. We’re about ready to try the first exercise for this lesson. First, however, there’s one more thing you need to know about form handlers before you can do the exercise.
Form Handlers
Forms are objects; they have their own methods, properties, and event handlers. One event handler that you should know about is onSubmit
. onSubmit
gets called in two situations:if a user clicks on a Submit button, or if a user hits Return in a text field. If these actions are not handled in some way, your JavaScript may behave differently than expected. Try clicking on
In Netscape, clicking on an unhandled Submit button generally leads to reloading the page. In general, you won’t want this. In order to block this behavior, you need to do this:
1 | <form onSubmit= "return false;" > |
3 | <input type= "submit" value= "Submit" > |
Generally, return false
is a way that JavaScript stops your browser from doing what it would otherwise do. Another example of this is stopping an href
from going to the URL assigned to it. For example, the link …
…. won’t go anywhere because you’ve returned false on the onClick.
Click on this dead link, if you don’t believe me.
This may seem like a weird thing to do, but actually it’s quite common, especially in the case of forms. Here’s an example of using a form to get input from a user. Type something into
this text field and hit Return.
Here’s the form:
1 | <form name= "text_entry_form" onSubmit= "monkeyLove(); return false;" > |
3 | <b>Who does the monkey love:</b> |
5 | <input type= "text" name= "monkey_love" size= "30" > |
When you hit Return in the text field, the onSubmit
handler gets called. It executes the function monkeyLove()
, which changes the value in the text field.
If the return false
wasn’t in the onSubmit
handler, the function monkeyLove()
would execute, changing the text field, but then the page would reload, changing the text field back to what it was. To stop this from happening, you need to have that return false
in the onSubmit
.
Here’s the monkeyLove()
function for your perusal:
05 | var who_it_is = window.document.text_entry_form.monkey_love.value; |
07 | who_it_is = 'The monkey loves ' + who_it_is; |
09 | window.document.text_entry_form.monkey_love.value = who_it_is; |
And here’s an example of the
same form without the return false, just so you can see what happens.
Once you’ve convinced yourself of the merits of return false
, it’s time to try a text-field exercise in part 2
No comments:
Post a Comment