How do you write pure JavaScript to listen to input value changes?
Most people new to JavaScript get confused about the different types of events when trying to listen to input value changes and are not sure what they all do.
So in this article I am going to show you how to setup an event listener for an <input>
element in your JavaScript code and help you decide on which event is the want you want to use.
Watch the video tutorial here.
Here’s a simple form that asks the user to enter their name and then should display it back to them in the message below the <input>
element.
<form>
<label for="yourNameInput">Please enter your Name:</label>
<input type="text" id="enteredNameDisplay">
<div>Hi <span id="enteredName"></span> nice to meet you!</div>
<button>Submit</button>
</form>
Of course we need to write some JavaScript to take the value of the <input>
field and then put it’s value
into the <span>
.
const yourNameInput = document.getElementById('yourNameInput');
const enteredNameDisplay = document.getElementById('enteredNameDisplay');
yourNameInput.addEventListener('input', (event) => {
enteredNameDisplay.textContent = yourNameInput.value;
});
The first argument to the addEventListener
function is the name or type of event we want to listen to. The second argument is actually a function itself and this will be run everytime the user taps a key on the keyboard whilst they are typing into the input element in the form.
It’s also important to note that the input
event also fires for things like copy and paste.
Here’s an example of the code working:
See the Pen Untitled by James (@codebubb) on CodePen.
So what are the other types of input events we can listen to?
Well, first off there’s the keyup
event which will behave the same as the input
event but will also be fired when any key is pressed such as SHIFT
, CTRL
etc.
There’s also keydown
which is fired before the input
element is updated so that might be useful if you want to get the previous value before doing something but doesn’t make much sense in our above example.
Then there is also the change
event which is only fired when the user loses focus from the input
element i.e. clicks or tabs out of the form field.