How To Display and Input Data From User Window Prompt in HTML and JavaScript? – POFTUT

How To Display and Input Data From User Window Prompt in HTML and JavaScript?

HTML Dom or JavaScript programming language provides Window.prompt()  which display a dialog with an optional message prompting the user to input some text. prompt() function is very useful for getting data from the user in real time or interactively. There are different ways to accomplish user data input from the browser but this is the simplest and easy way.

Syntax and Parameters

window.prompt() function has the following syntax where we have two parameters named message and default

  • result is the value input by the user interactively
  • message is the message which will be shown to the user with the input box
  • default is the value which will be set to the input by default.

Display Message To The User

As stated previously we can display or present a message to the user during the input. We will use the message parameter. In this example, we will print the message "Please Enter Your Age".

Display Message To The User

Display Message To The User

Different Ways To Call and Use prompt() Function

In the previous example, we have called prompt() function directly. But there are different ways to call prompt() function those are described below. All of the following examples are the same and there is no difference.

Set Default Value Display Input Field

prompt() function is mainly used to input or get a value from the user. In some cases, we may need to specify a default value which can be used by the user. We can specify the default value after the message. In this example, we will use default value 18 for the age.

Set Default Value Display Input Field

Set Default Value Display Input Field

Convert Input To Number

prompt() function will read given value from the user and return as a string type in JavaScript. If the user clicks to the Cancel button the returned value will be null which means there is no value. We can convert the inputted value into a number with the Number function which is used to convert a string to a number.

Leave a Reply

Your email address will not be published. Required fields are marked *

Enjoy this blog? Please spread the word :)