How to get multiple inputs to use key functions in Javascript/HTML?
How to get multiple input types to use the Enter key? This is my code.
//keypress enter
var input = document.getElementById("cost");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("calc").click();
}
});
As you can see, this code can only extract 1 element at a time.
2 answers:
Answer 0: (Score: 3)
Use to querySelectorAllselect all input type elements, and then apply a loop to assign event listeners to them:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("calc").click();
}
});
}
Answer 1: (Score: 2)
You just need to use getElementsByClassName to select all input elements, and then apply the event listener to all input elements. J
var input = document.getElementsByClassName("cost");
Array.from(input).forEach(function (element) {
element.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log("input changed")
}
});
});
<input class="cost"/>
<input class="cost"/>
//keypress enter
var input = document.getElementById("cost");
input.addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("calc").click();
}
});
As you can see, this code can only extract 1 element at a time.
2 answers:
Answer 0: (Score: 3)
Use to querySelectorAllselect all input type elements, and then apply a loop to assign event listeners to them:
var inputs = document.querySelectorAll("input");
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("keyup", function(event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("calc").click();
}
});
}
Answer 1: (Score: 2)
You just need to use getElementsByClassName to select all input elements, and then apply the event listener to all input elements. J
var input = document.getElementsByClassName("cost");
Array.from(input).forEach(function (element) {
element.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
console.log("input changed")
}
});
});
<input class="cost"/>
<input class="cost"/>
Comments
Post a Comment