Reputation: 33
I have an idea to create multiple inputs from single input and get their all values. But I can only get the first input value but not the rest. Can someone tell me how to do it?
const singleInput = document.getElementById('singleInput')
const demo = document.getElementById('demo')
const demo2 = document.getElementById('demo2')
const multipleInputValue = []
singleInput.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
demo2.innerHTML += singleInput.value + '<input
type="number"
class="multipleInput" onkeyup="getValue(event)">' +
'<br>'
multipleInput =
document.getElementsByClassName('multipleInput')
}
})
function getValue(event) {
if (event.key == 'Enter') {
multipleInputValue.push(multipleInput[0].value)
}
}
And here's the HTML Code for this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Coding</title>
</head>
<body>
<input type="text" id="singleInput">
<div id="demo">
<p id="demo2"></p>
</div>
<script src="script.js"></script>
</body>
</html>
Upvotes: 0
Views: 929
Reputation: 8163
Your getValue function (bound to onkeyup event of the input appended at runtime) was trying to get the value of the input with multipleInput[0].value
but no piece of code was pushing values to that array.
A better approach was to just using event.target
to retrieve the object firing the event from the event handler itself.
I showed here a simplified demo of your code showing that concept.
When you press enter on the first input, the second one will appear.. after then if you press keys inside that new input, a console.log will show the activity, including when you'll press enter (and the value will be pushed to the array).
But the overall logic wasn't pretty clear so I couldn't go any further
const multipleInput = [];
const singleInput = document.getElementById('singleInput');
singleInput.addEventListener('keyup', function (event) {
if (event.key == 'Enter') {
console.log('singleInput: pressed ENTER');
const inputElement = event.target;
const target = document.getElementById('target');
target.innerHTML +=
inputElement.value +
'<input type="number" class="multipleInput" onkeyup="getValue(event)"><br>';
}
});
function getValue(event) {
console.log(`Key was pressed for the new created input: ${event.key}`);
if (event.key == 'Enter') {
console.log(`The value pushed to the array is: ${event.target.value}`);
multipleInput.push(event.target.value)
}
}
.multipleInput{
margin-bottom: 1rem;
margin-left: 1rem;
}
#singleInput{
margin-bottom: 2rem;
}
<input type="text" id="singleInput">
<div id="target">
</div>
Upvotes: 1