Using prompt
The prompt method allows you to get information from the user. The method shows a model dialog with a confirm button and a cancel button attached to it and most importently it comes with a text field so a value can be typed into it and returned to you.
The following situation is going to activate the prompt method, which will ask the user to enter their name into it's entry field. (Once the user closes the dialog, the prompt method returns the value the user inserted into the entry field and then) this value is written to the document with an accompanying welcome back message. The example will also give the user some type of guidance by providing the value "name" in the entry field.
Run Code | View Code
Process
- Get the user's name -the prompt method of the window
- Write the user's name to the document with the welcome back message - use the write method of the document
Events
The document that is loading - body element loading procedure
Input
- The string displayed on the dialog - "Please enter your name"
- The string displayed (as the default value) in the entry field - "name"
- The welcoming string written to the document with the user's name - "Welcome back"
Event Trigger
The loading process of the body element in the document will come to the embedded script in the document that will start the "prompt" method and write the compiled massage to the document.
The Solution
Defined the body tag
<body>
</body>
Define the script container
<body>
<script language="javascript">
</script>
</body>
Define a global variable for the expected value
<body>
<script language="javascript">
var userName
</script>
</body>
Show the prompt method with the message "Please enter your name" with the default value for the text field being "name".
<body>
<script language="javascript">
var userName
userName = prompt("Please enter your name",'name')
</script>
</body>
Write the value of userName to the document with the "Welcome back" string.
<body>
<script language="javascript">
var userName
userName = prompt("Please enter your name",'name')
document.write("Welcome back: " + userName)
</script>
</body>
Run Code | View Code
See also Using confirm | Using alert | Making windows
Using alert
|
Using the status bar
|
Changing the background color of the document
|
Changing the content of a document
|
Using confirm
|
Changing the URL of a window Manually
|
Querying a text field's value
|
Checking the selected value of a select object
|
Checking if a checkbox is selected
|
Checking if a radio button is selected in a group
|
Making a rollover
|
Preloading images
|
Getting the time
|
Using setTimeout/setInterval
|
Making windows
|
Making cookies
JavaScript Tutorial Home