• No results found

Passing Information to the Function

In document Javascript Goodies (Page 142-150)

Lesson 26: Form Fields and the Value Property Lesson 27: Pull-Down Menu of Links

Lesson 28: A Guestbook with All the Bells and Whistles

Lesson 29: The Fifth End-of-Chapter Review—Posting Link Descriptions While Users Pass Over

Until this point, you have gathered information from the user mostly through a prompt.

This chapter looks at using JavaScript commands along with HTML form flags. Users will be able to enter their data into form fields and send the results along to you or use the form elements as new methods of choosing links.

I should state here that the following forms are all simply mailto:format scripts. We have not gone as far as attaching the output of the script to a CGI, as is commonplace today.

I mention that because Internet Explorer and Netscape Navigator handle mailto:forms dif-ferently. Netscape browsers enable you to submit a mailto:form and have the information

JavaScript Goodies

116

sent to an e-mail address as a packet. Internet Explorer, on the other hand, most likely opens a new mail message in whatever mail program you’re using.

Supposedly, IE 4.0 and better act on forms as Netscape does, but the user must have filled out all the mail preferences for it to work. You can’t always be sure of that.

The possibilities of what you can do with JavaScript and HTML forms are endless. Just remember that when using a form to submit information, IE users might have some trouble.

Lesson 23: What Is Written in the Text Box?

When you are dealing with form elements, there are three basic JavaScript events you want to be able to perform:

Extract the information from the fields so you can use it for other purposes.

Display information in a form element.

Send the information to yourself via e-mail.

This lesson deals with the first event. Someone has written something into a form field on your HTML document, and now you want to extract and display back to that person what she wrote in the field.

In this lesson, pay close attention to how the form elements are named and the format of the JavaScript hierarchy statement. Those two elements are, by far, the most important con-cepts in this lesson—and possibly this chapter.

The sample script is being displayed in full HTML format to show the placement of the ele-ments:

alert(“You wrote “ + document.myform.thebox.value + “ in the box.”) }

</SCRIPT>

</HEAD>

<BODY>

<FORM NAME=”myform”>

Write something in the box. <INPUT TYPE=”text” NAME=”thebox”><p>

<INPUT TYPE=”button” VALUE=”Then Click Here” onClick=”readit()”>

</FORM>

</BODY>

</HTML>

In Figure 5.1, I’ve entered my name into the box and clicked the button.

Figure 5.1

Displaying text box data.

To see the effect on your own computer click Lesson Twenty-Three Script’s Effect in your download packet, or see it online at http://www.htmlgoodies.com/JSBook/

lesson23effect.html.

Deconstructing the Script

When you start working with forms, the uses of the hierarchy statement and NAME attri-butes become very important. We will move through this script from top to bottom, often referencing from the function to the form elements.

The Function

The function’s purpose in this script is to take the information written to the text box and display it as part of an alert()box. It looks like this:

<SCRIPT LANGUAGE=”JavaScript”>

function readit() {

alert(“You wrote “ + document.myform.thebox.value + “ in the box.”)

JavaScript Goodies

118

}

</SCRIPT>

Thealert()format should be familiar. The new coding is the longer, more specific hierar-chy statement representing what is written in the box. The hierarhierar-chy statement reads like this:

document.myform.thebox.value

Without a more in-depth explanation, now let’s stop and look at the HTML form elements.

You need to become familiar with them to understand the hierarchy statement when we discuss it again. The FORMcode is as follows:

<FORM NAME=”myform”>

Write something in the box. <INPUT TYPE=”text” NAME=”thebox”><p>

<INPUT TYPE=”button” VALUE=”Then Click Here” onClick=”readit()”>

</FORM>

Here is each line of the form and what it means:

<FORM NAME=”myform”>is the overriding form command that starts the entire form process. The NAME=attribute gives the entire form a name. You must do this even if only one form is on the page—every form must have an overriding name.

<INPUT TYPE=”text” NAME=”thebox”>is the name of the form element you are most concerned with. This is the element where I typed in my name. The NAME=attribute in this case gives a name to the form element.

Now the form itself has a name, and the form element has a name. It is important that you make that separation in your mind. The form is now named myform, and the specific form element is named thebox.

<INPUT TYPE=”button” VALUE=”Then Click Here” onClick=”readit()”>is the button the user clicked to get the alert. The JavaScript in this button is an event handler that calls on the previous function, onClick=”readit()”.

</FORM>ends the HTML form section of the script.

Back to the Hierarchy Statement

Here is the hierarchy statement from the function, one more time:

document.myform.thebox.value

Remember that in hierarchy statements, things go from biggest to smallest, left to right. In this case, the hierarchy statement is narrowing down the items on the page until we get to the specific text I typed in the box:

documentrefers to the HTML document sitting inside the browser window.

myformis the name of the form on the page. Again, because only one form is on the page, this seems unnecessary, but this is JavaScript. You have to follow the syntax.

theboxis the name of the text box form element where I typed in my name.

valueis the JavaScript representation of what I typed in the box.

Now here’s the entire alert()command from the previous function:

alert(“You wrote “ + document.myform.thebox.value + “ in the box.”)

The format is very similar to what you did in earlier lessons. You gathered information from the user—usually in the form of a prompt—and then returned that value to the page through an alert()or a document.write.

This is exactly the same method, except you are gathering the text written into a text box through a hierarchy statement pointed right at the value.

The more things change, the more they stay the same.

The Entire Process

So, what is happening in this JavaScript?

The function is loaded into the browser’s memory, but nothing is actually done with it. It isn’t needed until the form button is clicked.

After something is typed into the form box, the user then clicks the button.

The button click triggers the function, which starts to post an alert box. However, if the button isn’t clicked, nothing happens. But let’s assume the user clicks the button. The text of the alert box calls for the value of a form element, thebox, inside a form, myform, on the current document.

After that data is retrieved, the alert box is posted—end of JavaScript.

Your Assignment

Your assignment should take a little bit of brainpower. Take the preceding script, and add a second text box to it. You’ll have to assign it a NAME, of course.

Then, get the alert button to pop up and read Hello firstname lastname!

You’ll get extra points if you can turn the long hierarchy statements into variable names.

You can see a possible answer to this assignment on your own computer by clicking Lesson Twenty-Three Assignment in your download packet, or see it online at http://www.

htmlgoodies.com/JSBook/assignment23.html.

JavaScript Goodies

120

Lesson 24: Passing Information to the Function

Now that you understand the concept of how to extract the value from a form item, let’s play with it a bit. This lesson’s script posts a series of alert boxes that tell you the values in the boxes, change the text to all uppercase, and then change it to all lowercase.

After all the alert boxes have finished, text will show up in a third text box thanking the user for watching the show.

The concept is this: If you can take information out of a form element, you can certainly put it back. Here’s the code:

<SCRIPT LANGUAGE=”JavaScript”>

function readitagain() {

var greeting=”Hello “

alert(greeting + document.myform.fname.value + “ “ + document.myform.lname.value)

alert(“length of first name “ + document.myform.fname.value.length)

alert(“First name in ALL CAPS: “ + document.myform.fname.value.toUpperCase())

alert(“Full name in all lowercase letters: “

➥ + document.myform.fname.value.toLowerCase() + “ “

➥ + document.myform.lname.value.toLowerCase())

document.myform.receiver.value= (“Thanks “ + document.myform.fname.value + “.”)

}

</SCRIPT>

<FORM NAME=”myform”>

What is your First Name? <INPUT TYPE=”text” NAME=”fname”><p>

What is your Last Name? <INPUT TYPE=”text” NAME=”lname”><p>

<INPUT TYPE=”button” VALUE=”Submit” onClick=”readitagain()”><P>

Look Here after Alert Boxes: <INPUT TYPE=”text” NAME=”receiver”><P>

</FORM>

Figure 5.2 shows the script’s effect.

You can try the script for yourself by clicking Lesson Twenty-Four Script’s Effect in your down-load packet, or see it online at http://www.htmlgoodies.com/JSBook/lesson24effect.

html.

Deconstructing the Script

Let’s start at the bottom and work our way back up the scale of the script. Here are the four form elements first:

<FORM NAME=”myform”>

What is your First Name? <INPUT TYPE=”text” NAME=”fname”><p>

What is your Last Name? <INPUT TYPE=”text” NAME=”lname”><p>

<INPUT TYPE=”button” VALUE=”Submit” onClick=”readitagain()”><P>

Look Here after Alert Boxes: <INPUT TYPE=”text” NAME=”receiver”><P>

</FORM>

The entire form has been named myform. That goes first, immediately following documentin the hierarchy statement.

The first text box is named fname. It contains the first name, which makes sense.

The second text box is named lname. It contains the last name. Again, that’s logical.

The input button is the familiar format. It is used to trigger the earlier function you calledreaditagain().

The third text box is named receiverbecause it receives something from the func-tion.

Okay, now you know the players, so let’s get to the plays found in the function.

Figure 5.2

This alert box changes a name to lowercase letters.

JavaScript Goodies

122

The Alert Boxes

Probably the easiest way to break down this script is to look at each element in the func-tion. You might have already noticed that the function is a long list of alerts that run one right after the other.

Finally, there’s a hierarchy statement pointing at something. We’ll look at that last. But first, here are the alerts:

var greeting=”Hello “

alert(greeting + document.myform.fname.value + “ “ + document.myform.lname.value)

The first alert shown in the preceding code uses a variable greetingto place the word Hello.

Do you find it funny that the variable name is longer than the actual word and space it’s representing? Me, too, but all this is to teach, so that’s how we did it.

Then, the first and last name are called for from the text boxes using the full hierarchy statements.

No surprises here:

alert(“length of first name “ + document.myform.fname.value.length)

Here’s something new. The alert posts the length, in letters, or whatever is entered in the first text box.

You might have taken it from the earlier lesson that valuewas at the end of the hierarchy food chain when it came to forms. That was true for that lesson, but not for all of

JavaScript.valuehas a couple of properties, actually; its length is just one of them. The JavaScript counts the letters, spaces, and any symbols in the value and posts the number it comes up with.

Luckily, in this case, JavaScript does not start counting at 0.

Once again, you see a familiar hierarchy statement with something stuck on the end of it:

alert(“First name in ALL CAPS: “ + document.myform.fname.value.toUpperCase())

This statement takes the information from the first name box and changes all the letters to uppercase.

It’s done by attaching the toUpperCase()method on the very end. Please note that toUpperCase()is a method, and you need those parentheses at the end.

If you can change letters to uppercase, it follows logically that you can change them to lowercase:

alert(“Full name in all lowercase letters: “

➥ + document.myform.fname.value.toLowerCase() + “ “

➥ + document.myform.lname.value.toLowerCase())

It’s done by following the same formula shown earlier, but you change the method at the end to toLowerCase(). Again, note the parentheses because toLowerCase()is a method.

Writing to the Text Box

Now you get to the most interesting part of this script. How did we get that text to show up in the text box? Here’s the line of code that did it:

document.myform.receiver.value= (“Thanks “ + document.myform.fname.value + “.”)

The concept is fairly straightforward. When you use the hierarchy statement

document.myform.receiver.valueas a return, you get the value of the text box returned.

But if you turn the process around and use the hierarchy statement as a target, as is being done in the previous code, the statement places the value rather than returning it.

That’s why the text in the instance pops into the box.

Your Assignment

Okay, smart person! Try to do this one:

Create a script that has two prompts. The first prompt asks for a name, whereas the second one asks for a home state.

After the two prompts have been filled in, two text boxes and a button should appear.

When the user clicks the button, the first text box should read Your name is name.

The second box should read You are from state.

Both effects should occur with one click of the button.

You can see a possible answer to this assignment on your own computer by clicking Lesson Twenty-Four Assignment in your download packet, or see it online at http://www.

htmlgoodies.com/JSBook/assignment24.html.

In document Javascript Goodies (Page 142-150)