Contents
It is important to know how to get user input in JavaScript in order to make your web applications more interactive. In this article, we will show you how to get input from the user and then use it in your web page.
Checkout this video:
Introduction
In this tutorial, we will learn how to get user input from the keyboard in JavaScript.
JavaScript offers several ways to get user input from the keyboard. The most common way is using the `prompt()` method.
The `prompt()` method displays a dialog box that prompts the visitor for input. The visitor can either enter a value or click “Cancel” to close the dialog box.
Here is an example of using the `prompt()` method:
“`javascript
var name = prompt(“Please enter your name:”);
“`
In this example, we are storing the value that the user enters into the `name` variable. If the user clicks “Cancel”, the `name` variable will be `null`.
Using the prompt() Method
The prompt() method displays a dialog box that prompts the visitor for input.
A prompt box is often used if you want the user to input a value before entering a page.
Note: When using the prompt() method, the browser displays a dialogue box that shows the message. The user will have to click either “OK” or “Cancel” to proceed after entering the input value. Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.
Using the confirm() Method
The confirm() method displays a dialog box with a specified message, along with an OK and a Cancel button.
A confirm box is often used if you want the user to verify or accept something.
Note: The confirm box takes the focus away from the current window, and forces the browser to read the message. Do not overuse this method, as it prevents the user from accessing other parts of the page until he/she has dealt with the modal dialog.
Using the alert() Method
The alert() method displays an alert box with a specified message.
This method can be used to display an information message, as well as a warning message or an error message.
The alert box takes the focus away from the current window, and forces the browser to read the message.
Do not overuse this method, as it prevents the user from accessing other parts of the page until the box is closed.
The alert() method can be written without the window prefix, as it is a global function.
Conclusion
There are three main ways to get user input in JavaScript:
-The element
-The HTML5 form-associated data API
-Via JavaScript itself (i.e. the window.prompt() method)
Each has its own advantages and disadvantages, so it’s important to choose the right one for your needs. In general, the element is the easiest and most compatible way to get user input, but the other two options are worth considering in some situations.