In this session of JavaScript Tutorial we'll look at the JavaScript prompt. The
prompt() is a method of
the window object in JavaScript, just like
JavaScript alert() or
JavaScript confirm().
Well, let's say we wanted to get somebody's name before they saw our page,
and then write their name on our web page right before their very eyes.......Well,
we can do this using a JavaScript prompt. Here's the command of JavaScript
Prompt.
Above line of JavaScript Prompt will bring up a window asking the question of your choosing,
with a space for the viewer to answer. The second set of quotes allows
us to enter any default answer. If we leave it blank, the viewer will
just see an empty box ready to be typed in. This is usually done before
the webpage loads, so that we can write the answer they give into our page.
Now, for the JavaScript that made this work. Note how the prompt and
if/else
statements are in the
HEAD section, while the actual writing of the name
occurs in the BODY section of webpage.
The first thing that happens is that the
JavaScript Variable enteredname is
assigned the value it receives from the user from the JavaScript Prompt.
So the
JavaScript Variable
enteredname will be a string of characters that makes up
the person's name. The if/else statement assigns
enteredname a value of
"Dude" if nothing is entered in the prompt by the user. It checks for " "
and for null, and both are pretty much nothing. Now, in the BODY section,
we again use the JavaScript SCRIPT tags to set off the JavaScript from any
HTML around it.
We will also see a new command called
document.write(" "); . This is what allows
the
JavaScript variable enteredname to be written onto the
HTML document.
We are writing two strings plus our variable,
enteredname. The
JavaScript variable enteredname
is not in quotes because it is a value and not itself a string but it's value is a
string. That's why we have the plus signs around it....It makes the browser write
the first string plus the
JavaScript variable plus the second string. Now, notice the
HTML tags
are inside the strings! Since this is a JavaScript, the only way to write the
HTML
tags back to the page is by including them inside the quotes as part of the string.
Also, we probably noticed the way the closing tags were written differently. (<\/H1>).
The backslash is there as the JavaScript escape character. It allows us to write the
forward slash without it being mistaken for a division sign! (Remember / is division in
JavaScript Tutorial). Thus using the backslash followed by a forward slash ultimately gives us.......
our single forward slash. Pretty nifty trick, isn't it?
Well, that does it for now. Let's go check out the above code and examine and
analyses in reality,
test your
self JavaScript Prompts Example.