I have created a calculator that makes a new row every time a button is clicked. In every new row generated are two input fields that users can input numbers and a div to show the resulting amount.
Calculation: (Input1 x Input2) - Input1
What I need help with is:
I am new to JavaScript and cannot find any answer that tells me how to target new elements created using the createElement functions. All I can find is how to create, append, remove or add a classList or a textNode.
const input1 = document.createElement("INPUT");
document.body.appendChild(input1);
const input2 = document.createElement("INPUT");
document.body.appendChild(input2);
const result = document.createElement("DIV");
document.body.appendChild(result);
an idea can be to use EventListener on the created input to manipulate the data
const input1 = document.createElement("INPUT");
document.body.appendChild(input1);
input1.addEventListener('change', function (e) {
var target = e.target || e.srcElement;
console.log(target.value);
});
you can also add a selector (id or class) to the created element and recover it by this selector
const input1 = document.createElement("INPUT");
document.body.appendChild(input1);
input1.id = 'test';
function showData() {
var input = document.getElementById('test');
console.log(input.value);
}
<button onclick="showData()">show data</button>
with your sample it can look like
const input1 = document.createElement("INPUT");
input1.id = 'input1';
document.body.appendChild(input1);
const input2 = document.createElement("INPUT");
input2.id = 'input2';
document.body.appendChild(input2);
const result = document.createElement("DIV");
result.id = 'result';
document.body.appendChild(result);
function showResult() {
var input1 = document.getElementById('input1');
var input2 = document.getElementById('input2');
var result = document.getElementById('result');
if (input1 && input2 && result) {
result.innerText = input1.value * input2.value;
}
}
<button onclick="showResult()">show result</button>
if you have to dynamically create div and showresult you can also create the button and manipulate the onclick event
function createNewRow() {
const input1 = document.createElement("INPUT");
input1.id = 'input1';
document.body.appendChild(input1);
const input2 = document.createElement("INPUT");
document.body.appendChild(input2);
const result = document.createElement("DIV");
document.body.appendChild(result);
const button = document.createElement("BUTTON");
button.innerText = 'show result';
button.addEventListener('click', function() {
result.innerText = input1.value * input2.value;
});
document.body.appendChild(button);
}
<button onclick="createNewRow()">create New Row</button>
OK, so the Id work, but it only works for that one row. I need to repeat that process (equation) independanly on each new row that's created.