reptile7's JavaScript blog
Saturday, June 04, 2005
The Prompt( ) Method
Blog Entry #11

The event handlers of HTML Goodies' JavaScript Primers #4 and #5 have given us our first taste of the interactive capabilities of JavaScript. Primer #6, which we address today, continues in an interactivity vein with the introduction of the prompt( ) method of the window object. You will recall that the Primer #4 assignment introduced the alert( ) method, which pops up a box with a message for the user. The prompt( ) method similarly pops up a box with a message, but unlike an alert box, a prompt box also, fittingly, 'prompts' the user for input that can be put to use in a separate command statement.

Primer #6's other main topic, JavaScript variables, was discussed previously in Blog Entry #5, so I won't belabor it here.

Let's get on with the prompt( ) method. On the aforementioned prompt box are four features:
(1) a message or query for the user;
(2) a text box-like field, for user input, which can have an initial "value" (message) if desired;
(3) an "OK" button in the lower-right-hand corner; and
(4) a "Cancel" button to the left of the "OK" button.

The basic syntax for popping up a prompt box is:

window.prompt("message or query for the user");

(As noted at the very end of Blog Entry #7, methods and properties of the window object do not need to reference the window object, and you will often see the command above written as: prompt("message or query for the user");.)

Text can be put in the user input field via a second prompt( ) subparameter, with a comma delimiting the two subparameters:

window.prompt("message or query for the user", "text in the user input field");

The second prompt( ) subparameter is optional. Contra the "The Prompt Command" section of the primer, it is not necessary to include a second set of quotes, and the box will not read "undefined" as a result.

Roll your mouse over these words for a demo.

On my computer, when using MSIE, the prompt box user input field, although not visually highlighted, is nonetheless 'selected' in the sense that pressing the delete key will clear it, replacing the text with focus in the form of a blinking vertical line (a.k.a. an insertion point cursor). Netscape, in turn, pops up a prompt box with a blinking vertical line already appearing at the end of the text in the user input field. (If the second prompt( ) subparameter is left out, then the prompt box pops up with only an insertion point cursor in the user input field, whether using MSIE or Netscape.)

The Primer #6 Script

Primer #6's focal point is the script below:

<script type="text/javascript">
/* This script is intended to take information
from the user and place it upon the page */

var user_name = prompt ("Write your name in the box below","Write it here");
document.write("Hello " + user_name + ". Welcome to my page!");


After an introductory comment (we discussed commenting in JavaScript in Blog Entry #6), the script pops up a prompt box that asks for the user's name. The user deletes the "Write it here" text in the user input field and then types in a name. If and when the user clicks the "OK" button on the prompt box (we'll get to the "Cancel" possibility shortly), then the inputted user name is assigned, as an 'output', to the variable "user_name".

Subsequently, the document.write( ) statement makes use of the "user_name" variable, splicing it, as a subparameter, with two text strings in order to write "Hello name-inputted-by-user. Welcome to my page!" on the page.

(The Primer #3 script featured a document.write( ) statement that acted on variable-containing commands, but this is the first time we have seen a variable by itself appear in the write( ) parameter.)

It's not necessary to variabilize the output of the prompt command. Joe could have written:

document.write("Hello " + prompt("Write your name in the box below","Write it here") + ". Welcome to my page!");

Use of a variable makes the code a bit easier to follow, however.

If the user clears the input field and clicks "OK" without entering a name, then the output does not contain "null" but simply reads:

Hello . Welcome to my page!

however, if the user responds to the prompt box by clicking the "Cancel" button, then the output is indeed:

Hello null. Welcome to my page!

"Null" is a JavaScript reserved word and can be classified as a data type; it is roughly synonymous with "empty". If a variable has the value "null", then it has no value, or more precisely, it has a valid "value of no value". (A "null" variable thus has a more definite status than does an "undefined" variable, which in a script appears as a placeholder but is otherwise characteristicless.) In this case, the prompt( ) method output, variabilized or not, has no value and is thus "null" when acted on by the document.write( ) command.

Let me lastly address something Joe says at the outset of the primer, in the "The Concept" section: "we're now back to creating full JavaScripts rather than just adding Events to HTML, so we'll need to once again start using the full <SCRIPT type="text/javascript"> to </SCRIPT> format." As we saw above, however, prompt( ) commands can definitely be assigned to event handlers. As a second example, consider the code below, which is patterned on the Primer #6 script and even includes the use of a variable:

<span onclick="var colour = window.prompt('What is your favorite color?','Enter a color here'); style.color = colour;">Click on this sentence to change its text color.</span>

Try it out:

Click on this sentence to change its text color.

(The Primer #6 script itself can be executed by an event handler, although the end result is a bit strange in that the document.write( ) output supersedes the rest of the page - click here to see it for yourself.)

The end-of-primer assignment and its answer

Joe asks the reader to 'deconstruct' a script that obtains the reader's first name and the date and then writes them, as part of a sentence, to the title bar of the browser window.

You will notice that the script does not execute as advertised, i.e., the title bar reads "Assignment 6", and not "Hi name-inputted-by-user  Today's date is m/d/y  Thanks for coming". Why might this be?

Check the source code of Joe's "Assignment 6" page. Near the top, we have:

<TITLE>Assignment 6</TITLE>

On my computer, the needed corrective action is browser-dependent. When using MSIE, if I delete the "Assignment 6" between the <title> tags (so that nothing or only whitespace is there), or remove this line altogether, then the script works fine. Netscape requires me to remove the entire line.

In the answer, Joe notes that "this script must go above the BODY command in the HTML document, because that's where the TITLE goes." Up to this point, we haven't said anything about whether a given JavaScript script should be placed in the <head> or the <body> part of the document - oftentimes, it doesn't matter, and this is one of those times. Checking the source code once again, we see that the Assignment 6 page has neither <head> nor <body> tags. But the important thing, as we just noted, is to get rid of the "Assignment 6" title, which overrides the <title> commands of the script.

The scripting of the Assignment 6 page is noteworthy in other ways:

(1) In the main script, we see the returns of two different commands assigned to the same variable name, "d". The second statement creates a new Date object and assigns it to "d". Three statements later, the d.getDate( ) return is in turn assigned to "d". After the fifth statement, "d" in the script represents not the Date object but the new Date( ).getDate( ) return. Needless to say, the use of "d" here is algebraically unsatisfying (or at least I find it to be), but it is legitimate in JavaScript for a script to utilize a given variable name more than once in this manner.

(2) In extension of the main script, Joe sprinkles the user's name throughout the page text with the code:

<SCRIPT>document.write("" +name+ "")</SCRIPT>

Presumably, the quotes in the write( ) parameter are there to ensure that the "name" variable is recognized as a text string by the document.write( ) command, but I found that I could remove the quotes and use:


without any problems. Anyway, what grabs my attention here is that the value of "name", once set in the main script, 'crosses over' to subsequent, separate scripts. Less importantly, we can also conclude that the browser will recognize and execute a JavaScript script even if the opening <script> tag lacks a language="javascript" or type="text/javascript" attribute. (I applied this to the main script, removing type="text/javascript" from its <script> tag, and it reran OK.) I have no idea if this is true for other types of scripts or not.

But speaking of "main" and "subsequent" scripts, it's possible for the entire page to be one big script, using the following code:

<script type="text/javascript">
var name = window.prompt("Please write in your first name");
var d = new Date( );
var y = d.getFullYear( );
var m = d.getMonth( ) + 1;
var d = d.getDate( );
var t = m + '/' + d + '/' + y + ' ';
document.write("Hi "+ name + " Today's date is " + t + "Thanks for coming");
document.write("Hi, " + name + ". We've been expecting you, etc.");

We see from the above that a script can straddle the head and body parts of a document - click here to see it in action.

Finally, some nitpicking about the script deconstruction on the answer page (the temptation is there to go through this line by line, but the points I would make have been already covered, directly or indirectly, above and in previous entries, so I'll limit myself to the following):

(a) The fifth bullet point (• See the "+ 1900" after the year?...) should be deleted; it refers apparently to an earlier version of the primer that used the now-deprecated getYear( ) method instead of the getFullYear( ) method.

(b) The sixth bullet point should read:
• See that "+ 1" at the end of the "m" variable? That's a trick that sets the year month to the correct count. It's a good idea to use it when you ask for the month.

Properties, properties, properties...they're the focus of HTML Goodies' JavaScript Primers #7, which we'll thrash out in our next episode.


Comments: Post a Comment

<< Home

Powered by Blogger

Actually, reptile7's JavaScript blog is powered by Café La Llave. ;-)