Ken Ward's Java Script Tutorial ...

Prompting for User Input

Click here to see an example of the prompt!

The previous alerts have been a way of giving information to the user. The prompt asks for information from the user to input into the script. In the example above, the prompt asks for the user's name. The name is then used to write the page.

Press the button below and see what happens!

When I press this button it asks me my name. I don't bother to say, being a rather reserved character, so it uses the default, in this case, Ezekial, and gives a welcome message. If you don't want to be called Ezekial, then enter a more suitable name.

The Code

Here is the code from the HEAD of this page:

<script type="text/javascript">


function prompter()


name=prompt('What\'s your name?',"Ezekial");

Response=alert("Welcome "+name);




This is the code for the prompt:

prompt('What\'s your name?',"Ezekial")

The first bit between the single quotes is the question the user is asked, in this case, 'What's your name?' Note the \ to tell the browser that the apostrophe is text! The next bit in quotes is the default, which in this case is Ezekial.

Next there is a variable called name. We make the prompt equal to the name variable so it stores the data which the user enters. If the user doesn't enter any, then the name Ezekial is used.

So now we have a variable called name with a value equal to the name Ezekial or the user's name or both (if they are the same):

name=prompt('What\'s your name?',"Ezekial")

The last line in the head code is where we create the alert message:

Response=alert("Welcome "+name)

Or rather we put in the variable Response 'Welcome' plus the users response.

Finally, we put this code in the BODY of the document where we want the button:

<form action="">

<input type="button" name="b1" id="b1" value="What\'s your name" onclick="prompter()" />


This is a standard button in a form with the onClick event calling the function 'prompter'. When prompter is called, the variable name holds the user's name, the variable Response holds the message we want to display as an alert button, which pops up as you have seen! The "id", which is a duplicate of the "name", is there to make the code compatible with XHTML.

Easy isn't it?

You know what is hard? This is what is hard:

Yes, Java Script is easy. The problems we have are the same problems we have with everything else - spelling and the like!

Let's look at Writing with Java Script!

And for some programming for your brain: check out New Life Course