Apps/Gaming

JavaScriptInput

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.

Reading: 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 other Cancel buttons. clicking OK returns the current (default or user supplied) input value, while clicking Cancel returns zero.

Programmers can check that a non zero 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) { document.getElementById(“greeting”) .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’s 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 buttons:

JavaScript confirmation dialog 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 ? “Payments sent!” : “Payment cancelled!”;

Reading: 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 ninjaunits.com that converts pixels to rem:

ninja units

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:




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 other 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’); fnameInputStream$ .pipe( merge(lnameInputStream$), debounceTime(500) ) .subscribe(event => { console.log(event.target.value); const name = fname.value + (lname.value.length > 0 ? ” ” + lname.value : “”); messages.innerHTML = “Hello ” + name + “! Nice to see you!”; });

Just like the ninjaunits.com site, processing may occur before the user has entered his or her full name, resulting in a partial name, such as “grave“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 on change 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 are focused on the text input, keep in mind that there are numerous other native HTML form controls to choose from, including the larger ones textarea element, drop-downs, radio buttons, and checkboxes. Moreover, frameworks like Angular materials have added a wealth of custom controls such as sliders, calendars, slide toggles, and lots more!

Reading: Top JavaScript frameworks

Related posts

Project management methodologies

TechLifely

Python: Extracting Text from Unfriendly File Formats

TechLifely

Teamwork Project Management Alternatives

TechLifely

Leave a Comment