Javascript Tutorials

XMLStyleSoldierFlowerMonkey

Getting Input from a User

Web sites often need to receive input from their users in order to personalize their sites. For example, when you want to ask the user for their name when they first visit your site, you can use something called a "prompt box;" no, not a lock box, a prompt box. =)

Sponsors - Spoono Host
Prompt Boxes

The basic javascript syntax for a prompt box is:

<script language="Javascript">
prompt("Prompt Box question","Default Value")
</script>



All right, now you ask how to get information from the prompt box and store it in the variable. The syntax for that is found below:

<script language="Javascript">
var name = prompt("What is your name","Type Name Here");
</script>

Now, there are two things that you need to know here. The "var name" parts simultaneously declares a variable called name and assigns it to the value of whatever is put in the prompt box. Also, notice the semicolon (;) after the prompt box line. This is standard syntax when declaring a variable.

Great, so now you have this variable called name with a user's name in it. Now you want that name to be displayed in a text box. This is how it is done:

<form name="myform">
<input name="mytext" type="Text" size="50">
<input type="button" onclick="input()" value="Go">
</form>

I first created a form with the standard form, input box, and submit button with the standard syntax. Now, in the onclick event, I made the button execute the input() function which is below:

<script>
function input()
{
var name=prompt("What is your name?","Type Name Here");
document.myform.mytext.value=name;
}
</script>


All I did here was tell the button to put the value of the variable name into the value of the "mytext" input box using the document.myform.mytext.value=name;. This is self-explanatory syntax and would be trivial to explain it. Below is a little thing I put together for you guys. That's it, have fun with prompt boxes and input!


Discuss this tutorial »
Written by: Brian Fusco
Back to Javascript TutorialsTop


Copyright © 2000-2010 Spoono, LLC. All rights reserved.
Network: Reseller Web Hosting by Spoono Host | Spoonloads | Absolute Cross
Terms of Service | Privacy Policy.

kdfj