Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to get the value of an input field in JavaScript

In this blog post, we will dive into the world of JavaScript and learn how to get the value of an input field. This is a common task that developers face, especially when building interactive web applications that require user input, such as forms or search bars. If you are new to programming or just starting with JavaScript, don't worry! We will break down the concepts and provide clear explanations and code examples to help you understand.

What is an input field?

An input field is a text box that allows users to enter data into a web application. You might have seen them in forms, where users provide their name, email address, or other information. Input fields are created using the HTML <input> element, which comes in different types, such as text, password, email, etc. In this post, we'll focus on the most common type, which is the text input field.

What is JavaScript?

JavaScript is a programming language that is used primarily for adding interactivity to web pages. It allows you to manipulate the content and structure of HTML and CSS, respond to user actions, and even communicate with web servers.

Accessing the HTML input field in JavaScript

Before we can get the value of an input field, we first need to access the input field element in our JavaScript code. To do this, we can use the document.querySelector() method. This method allows you to locate an HTML element using a CSS selector.

Imagine you have an HTML input field like this:

<input type="text" id="my-input" placeholder="Enter some text">

To access this input field using JavaScript, you would use the following code:

const inputField = document.querySelector('#my-input');

In this example, we used the #my-input CSS selector to target the input field with the id attribute of my-input. The document.querySelector() method returns the first element that matches the specified selector - in this case, our input field.

Getting the value of an input field

Now that we have accessed the input field, we can retrieve its value using the value property. This property holds the current text that is entered in the input field. Here's an example:

const inputField = document.querySelector('#my-input');
const inputValue = inputField.value;

console.log(inputValue); // This will log the value of the input field to the console

In this example, we accessed the value property of the inputField object and stored it in the variable inputValue. We then logged the value to the console using console.log().

Reacting to user input with event listeners

It's often useful to update the page or perform some action when the user enters a value in the input field. To do this, we can use event listeners. An event listener is a function that "listens" for a specific event, such as a button click or a keypress, and performs a specified action when that event occurs.

In our case, we want to listen for the input event on the input field. The input event is fired whenever the user types or otherwise changes the value of the input field. To listen for this event, we can use the addEventListener() method. Here's an example:

const inputField = document.querySelector('#my-input');

inputField.addEventListener('input', (event) => {
  const inputValue = event.target.value;
  console.log(inputValue); // This will log the value of the input field every time it changes
});

In this example, we added an event listener to the inputField object. The addEventListener() method takes two arguments: the event type (in this case, 'input') and a callback function that is executed when the event occurs. The callback function receives an event object, which contains information about the event, such as the target element (the input field) and the type of event.

Inside the callback function, we accessed the value property of the target element using event.target.value and logged it to the console. Now, the value of the input field will be logged every time it changes.

A real-world example: searching a list of items

To further illustrate how to get the value of an input field and use event listeners, let's create a simple example application. Imagine you have a list of items, and you want to filter the list based on the user's input. Here's the HTML structure for our example:

<input type="text" id="search-input" placeholder="Search for an item">
<ul id="items-list">
  <li>Apple</li>
  <li>Banana</li>
  <li>Carrot</li>
  <li>Donut</li>
  <li>Egg</li>
</ul>

In this example, we have a text input field with the id attribute of search-input and an unordered list (<ul>) with the id attribute of items-list. The list contains five list items (<li>).

Now, let's write the JavaScript code to filter the list based on the user's input:

const searchInput = document.querySelector('#search-input');
const itemsList = document.querySelector('#items-list');
const items = itemsList.querySelectorAll('li');

searchInput.addEventListener('input', (event) => {
  const searchValue = event.target.value.toLowerCase();

  items.forEach((item) => {
    const itemText = item.textContent.toLowerCase();
    const isMatch = itemText.includes(searchValue);

    item.style.display = isMatch ? '' : 'none';
  });
});

In this example, we first accessed the searchInput and itemsList elements using the querySelector() method. We also created a variable called items that contains all the <li> elements within the itemsList element. We used the querySelectorAll() method to get all the elements that match the specified selector - in this case, 'li'.

Next, we added an event listener to the searchInput element, listening for the input event. Inside the callback function, we got the value of the input field and converted it to lowercase using the toLowerCase() method.

We then looped through each item in the items variable using the forEach() method. For each item, we got its text content using the textContent property and converted it to lowercase. We then checked if the item's text includes the search value using the includes() method, which returns true if the search value is found in the item's text, and false otherwise.

Finally, we updated the display property of the item's style object based on whether the item's text matches the search value. If the item's text includes the search value, we set the display property to an empty string (''), which means the item will be visible. If the item's text does not include the search value, we set the display property to 'none', which hides the item.

Now, when you type in the search input field, the list will be filtered based on your input!

Conclusion

In this blog post, we learned how to get the value of an input field in JavaScript. We covered the basics of accessing HTML elements, using event listeners to react to user input, and updating the page based on the input value. With this knowledge, you can now start building more interactive web applications that respond to user input in real-time.

Remember, practice makes perfect! Keep experimenting with different HTML structures, JavaScript methods, and event types to gain a deeper understanding of how everything works together. Happy coding!