Select Page

JavaScript Input |

Robert Gravelle
Published: January 21, 2023

JavaScript’s greatest strength is its ability to accept user information and process it within the browser. As such, it is a wise coder who spends time learning to read user input and employ the correct syntax to work with that input. This web developer tutorial focuses on retrieving user input through prompts and the HTML text input element.

Read: Best Online Courses to Learn JavaScript

How to Retrieve User Responses from a Prompt in JavaScript

JavaScript offers a few global methods for acquiring information from your users. For instance, the window.prompt() method displays a modal dialog that takes input from a user to be used in your JavaScript code. The prompt() method is meant for small amounts of information, such as a first and last name. For large blocks of text or complex data, you should use an HTML form. It is most useful for gathering just a bit of data before navigating to another page or performing some action that requires the data.

prompt(text, defaultText)
  • The text argument is optional and specifies the text to display in the dialog box.
  • The defaultText argument is also optional and specifies the default input text.

Here is some example JavaScript code that prompts the user for his/her name:

var name = prompt("Please enter your name", "Bill Smith");

The prompt dialog contains an OK and Cancel button. Clicking OK returns the current (default or user supplied) input value, while clicking Cancel returns null.

JavaScript prompt()

Programmers can check that a non-null value was received before processing it. The following code displays a greeting that checks for a non-null value using JavaScript:

var name = prompt("Please enter your name", "Bill Smith");

if (name != null) {
    .innerHTML = "Hello " + name + "! Nice to see you!";

Although you can preface the method with the window object – window.prompt() – there is no need because it is the default global namespace.

The Confirmation Dialog in JavaScript

If you only need to get confirmation from the user consider using the Confirmation Dialog. It is a quick way to get confirmation without using any complex coding logic. The confirm() method displays a dialog box with a message, an OK button, and a Cancel button:

JavaScript Confirmation Dialogue Box

The confirm() method accepts only one argument: an optional message to display in the confirm box:

confirm("Are you sure you want to send a payment of $25?");

The message can also contain line-breaks:

confirm("Press a button!\nEither OK or Cancel.");

The confirm() method returns true if the user clicks “OK“, while pressing “Cancel” returns false.

Here is some code that employs the confirm() method to verify that the user wishes to proceed with a payment and sets a message based on the result:

var res = confirm("Are you sure you want to send a payment of $25?");
messages.innerHTML = res === true ? "Payment sent!" : "Payment cancelled!";

Read: JavaScript Output

Using a Text Input Control in JavaScript

Originally part of HTML Forms, elements like textboxes, drop-downs, checkboxes, and radio buttons were employed to collect user input to be sent to a server for processing. As developers gradually began to capitalize on JavaScript’s tremendous client-side processing power, form controls were taken out of the Form element and utilized to gather information for processing within the page. Case in point, thousands of web pages host converter utilities like this one at that converts pixels to rem:



Notice the conspicuous absence of a Submit button. User input is read via the keyup event so that the Result in Rem field is updated in real time. A short debounce (delay) gives the user time to enter a value and prevent excessive calls to the calculation logic.

We can follow the same approach to acquire our visitor’s name using a couple of (first and last name) text input fields:

<label for="fname">First name:</label><br>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label><br>
<input type="text" id="lname" name="lname">

<h2 id="messages"></h2>

The debounce part is made quite a bit easier using JS library like RxJS. Though synonymous with frameworks like Angular and ReactJS, you can add RxJS to any HTML page via CDN.

The following code creates an input stream from the fname and lname input fields, which are then merged together before adding a half second debounce. Once the subscribe() method receives the event, it logs the latest value received from either input field, and updates the message:

//Using RxJS version 7.8.0
const { fromEvent } = rxjs;
const { merge, debounceTime } = rxjs.operators;

const fname = document.getElementById("fname");
const lname = document.getElementById("lname");
const fnameInputStream$ = fromEvent(fname, 'keyup');
const lnameInputStream$ = fromEvent(lname, 'keyup');

  .subscribe(event => {
    const name = fname.value + (lname.value.length > 0 ? " " + lname.value : "");
    messages.innerHTML = "Hello " + name + "! Nice to see you!";

Just like the site, processing may occur before the user has entered his or her full name, resulting in a partial name, such as “Grav” instead of “Gravelle“:

JavaScript User Input Tutorial

Of course, the message will be updated every half second until the user has finished typing, at which point the entire name will be displayed.

If you do not want to deal with partial names, there are options, the easiest of which is to hook into the last name input’s onblur or onchange event rather than onkeyup. Another, more elaborate option would be to display the message after a lull in activity, say two or three seconds.

You can see all of the code from this JavaScript tutorial, plus an example on how to display the message after a lull in activity, in action in the codepen demo.

Final Thoughts on JavaScript Input

While we focused on the text input, keep in mind that there are numerous other native HTML form controls to choose from, including the larger textarea element, drop-downs, radio buttons, and checkboxes. Moreover, frameworks like Angular Material have added a wealth of custom controls such as sliders, calendars, slide toggles, and lots more!

Read: Top JavaScript Frameworks