JavaScript, the language of the web, empowers developers to create interactive and dynamic web applications. One of the fundamental aspects of designing a web app involves gathering user input, which enables users to interact with and control the web application. This article will show you how to use various JavaScript functions often used to get user input.
Table of contents
- What is JavaScript?
- How to get user input
- The prompt() method
- addEventListener() method
- Event listeners on HTML forms
- Conclusion
What is JavaScript?
JavaScript is a versatile programming language primarily used for web development. It was created by Brendan Eich in 1995, and JavaScript has since become one of the core technologies of the World Wide Web, alongside HTML and CSS.
The name first given to the language was Mocha, renamed LiveScript in September 1995. In December of the same year, it was officially announced as JavaScript.
So, how can JavaScript be used? It can be embedded within HTML documents using <script> tags. It can also be included as an external JavaScript file. That means developers can write JavaScript code inline or organize it into separate files for better maintainability and reusability.
How to get user input
Let’s discuss how we can gather user input using JavaScript. It turns out that there are several ways to do that. Here are some of them:
- Using the
prompt()method - Leveraging the
addEventListener()method - Employing event listeners on HTML forms
Next, we will discuss the above methods in more detail to better understand how they can be applied in real life.
The prompt() method
The prompt() method displays a dialog box with a message prompting the user to input text. It’s simple to use and suitable for gathering single inputs such as a user’s first name, last name, or date of birth.
The following code demonstrates how to use this method:
// Prompt with default text for the user's name
let userInput = prompt("Please enter your name:", "automateNow");
if (userInput !== null) {
// Handle user input
console.log("Hello, " + userInput);
} else {
console.log("The prompt was closed by the user.");
}Code language: JavaScript (javascript)
The let keyword keyword is used to declare variables. Unlike the older var keyword, let allows you to declare block-scoped variables. Variables declared with let are only accessible within the block in which they are defined.
In this example, we use let to create a userInput variable, which stores what the user enters in a prompt. The prompt() method uses two parameters. The first displays a message asking the user to enter their name. The second parameter, which is optional, serves as the default value if the user chooses not to enter anything in the input field.
The addEventListener() method
The previous example used a very common method. This example has another common method, addEventListener(), which is commonly used to listen for events on DOM elements. It can capture user input from various interactions, such as clicking a button or submitting a form. Check out our test automation practice website to practice the following example.
// Store reference to input element
let inputField = document.getElementById("name");
// Add event listener to input element
inputField.addEventListener("change", function(event) {
let userInput = event.target.value;
console.log("User input:", userInput);
});Code language: JavaScript (javascript)
In this example, we use an internal JavaScript function, document.getElementById(), to store a reference to the element used for the user’s input. We then use another built-in function, addEventListner, to add an event listener to an input field with the unique ID of name. Whenever the value of this input field changes, the event listener captures the new value and logs it to the console.
Using Event Listeners on HTML forms
Now, let’s learn how to use HTML forms to capture user input. HTML forms offer a structured way to collect multiple inputs from users. You can capture user input efficiently by attaching event listeners to HTML elements on forms.
Here is how to do that:
<form id="userForm">
<input type="text" id="username" placeholder="Enter your username">
<button type="submit">Submit</button>
</form>
<script>
document.getElementById("userForm").addEventListener("submit", function(event) {
event.preventDefault();
let username = document.getElementById("username").value.trim();
console.log("Submitted username:", username);
// Further processing or validation can be done here
});
</script>Code language: JavaScript (javascript)
Tip: Use a textarea element if you need to capture large blocks of text.
In this example, an event listener is added to the form element. When the form is submitted, the event listener prevents the default form submission behavior (event.preventDefault()), retrieves the value of the username input field, trims any leading or trailing whitespace, and logs the username to the console.
What if you want to know when a user clicks a button? Here is an example that uses the onclick event listener to show an alert when a button is clicked:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>onclick Event Listener Demo</title>
<style>
#myButton {
padding: 10px 20px;
font-size: 16px;
cursor: pointer;
}
</style>
</head>
<body>
<button id="myButton">Don't Click Me!</button>
<script>
// Get reference to the button element
const button = document.getElementById("myButton");
// Add onclick event listener
button.onclick = function() {
// Code to execute when the button is clicked
alert("Why did you do that?!");
};
</script>
</body>
</html>Code language: JavaScript (javascript)
This example has an HTML button element with the id myButton. For fun, we added a button label of “Don’t Click me!”. We first get a reference to the button element using document.getElementById(). Then, we attach an event listener to the button using the onclick property. When the button is clicked, the function assigned to onclick is executed. The code also includes some CSS style info for the button.
Inside the event listener function, we have a simple alert message that pops up saying, “Why did you do that?!” when the button is clicked. This demonstrates the basic usage of the onclick event listener to perform an action in response to a button click event.
Final thoughts on getting user input in JavaScript
Knowing how to properly capture user information in JavaScript is crucial whether you’re building a simple Contact Us web page or a form with sophisticated input data. By understanding and utilizing methods like prompt(), addEventListener(), and event listeners on HTML forms, web developers can create engaging user experiences.
Whether collecting simple text input, user feedback, or handling complex forms, JavaScript provides great flexibility to gather and process user input effectively. Now, go and practice what you’ve learned here to create an amazing user experience!
Follow our blog
Be the first to know when we publish new content.
How to take user input in JavaScript?
- How to Exit A Program in Java - June 16, 2024
- How to Get User Input in JavaScript - June 7, 2024
- How To Calculate Percentage In Java - June 1, 2024