Easily obtain user input in Javascript using the prompt function

Easily obtain user input in Javascript using the prompt function

Get user input by displaying an input dialog using the prompt() function in Javascript


There are many different ways of obtaining user input in Javascript, one of the simplest ways is to use the prompt() function to generate a dialog box. This dialog box can be created with a customized message and an input placeholder.


Obtaining user input and storing it using the prompt function


The prompt() function works by displaying a dialog box with an input, it pauses the execution of your script until the user has entered a value into the input and either pressed enter, clicked the "ok" button or the "cancel" button.


If the user enters a value and either presses enter or clicks the "ok" button, then the value will be returned and it can be stored in a variable (or used some other way). If the user does not enter a value and presses enter or clicks the "ok" button, then an empty string will be returned. If the user presses the cancel value, then it will return

null

.


Basic syntax

prompt( dialog_text, optional_input_placeholder );


The input placeholder argument is optional.


As an example, let's create a simple input dialog that will ask the user for their name. The given value will then be stored in a variable.


var name = prompt( "please enter your name", "type here" );   
   
alert( "hello " + name );   

This will create a dialog box similar to the one below:




Christopher Thornton@Instructobit 7 years ago
or