Parameters
Parameters are the information that a JavaScript command needs in order
to operate. Taking the alert as an example:
alert("Hello world")
The prompt command is followed by a pair of brackets which enclose the text to be
displayed. NotePad++ will highlight matching pairs of brackets. Select the closing
bracket and you'll see that both it and the matching opening bracket will light up in
red.
The strings between the brackets are the parameters that are being passed to the
prompt method. We'll be talking more about parameters when we get on to functions but for
now it's enough to know that prompt needs to have these two strings in order to do its
work.
The first parameter is the message to be displayed, in this case it's "What is your
name?". We've not used the second parameter yet but this is the default value that
will be displayed in the input area of the prompt. We've just given an empty string
and so the box has been blank. Edit day4a.html and add the second parameter to
the prompt command:
userName = prompt("What is your name", "Fred");
alert("Hello " + userName + ".");
Save this as day4b.html and run it. You should see that the prompt box comes up
suggesting "Fred" as the name to be entered. It's not a very useful example but if
you're asking the user how many books they want to buy from your website then:
numberRequired = prompt("How many books do you want?", "1");
would be helpful because most users are going to want one book.
|