This code is easier to understand when you break the code out to a separate function.
However, if coding this from scratch, an improved solution is easily achieved without needing id attributes at all.
<ul>
<li>1:<input type="text"> gives:<span></span></li>
<li>2:<input type="text"> gives:<span></span></li>
<li>3:<input type="text"> gives:<span></span></li>
<li>4:<input type="text"> gives:<span></span></li>
</ul>
We can get all of the li
elements and loop over them with:
var items = document.querySelectorAll("li");
Array.from(items).forEach(function (item) {
...
});
For each of the items, we want to get the input and span. The addEventListener()
method is the proper and correct way to add event listeners, and we’ll be passing input
and span
to a wrapper function designed to gives us an appropriate handler method.
...
Array.from(items).forEach(function (item) {
var input = item.querySelector("input");
var span = item.querySelector("span");
item.addEventListener("keypress", inputKeypressWrapper(input, span));
});
The inputKeypressWrapper()
function will return a function. Thanks to a technique called closure, that returned function retains knowledge of the input and span.
function inputKeypressWrapper(input, span) {
return function inputKeypressHandler(evt) {
...
};
}
Lastly, it is within the inputKeypressHandler()
function where we handle the keypresses.
The keyCode
and which
methods are now deprecated and have been removed from web standards, so we need to use better ones like code or key instead. These give string values for pressed keys.
If we use code
we’ll get “Enter” or “NumpadEnter”, whereas with key
we’ll just get “Enter”, so that’s the more suitable one to use in this case.
And lastly, we can just use innerHTML to replace the contents of the span element. We can use this
in there, but the code is easier to understand when we actually see that it’s the input instead.
...
return function inputKeypressHandler(evt) {
if (evt.key === "Enter") {
span.innerHTML = input.value;
}
};
...
Here’s the full code:
function inputKeypressWrapper(input, span) {
return function inputKeypressHandler(evt) {
if (evt.key === "Enter") {
span.innerHTML = input.value;
}
};
}
var items = document.querySelectorAll("li");
Array.from(items).forEach(function (item) {
var input = item.querySelector("input");
var span = item.querySelector("span");
item.addEventListener("keypress", inputKeypressWrapper(input, span));
});
It can easily be modified to suit different conditions too. For example, when you have other items on the page, placing a class name on the ul
element allows you to easily restrict the code to only that area:
<ul class="showOnEnter">
var list = document.querySelector(".showOnEnter");
items = list.querySelectorAll("li");
...