As someone who is new to Javascript, I am embarking on the journey of creating a unit conversion calculator. My goal is to loop through a table and assign an onclick event that will display the value of the clicked button.
So far, I've managed to obtain a NodeList which I am iterating through. However, when I add the onclick event, each button click only outputs the value of the last button in the list.
var x = document.getElementsByName("Scalar")
var out = document.getElementById("output")
function Edit(Input){
out.innerHTML = Input;
}
var i;
for (i = 0; i < x.length; i++) {
out.innerHTML = out.innerHTML + x[i].name;
var b = x[i];
b.onclick = function() {
Edit(out.innerHTML + b.value)
}
}
<input type = "button" id="Scalar" value = "K" name = "Scalar"/>
<div id="output">
</div>
When I click any button, my output ends up being the value of the last button in the list (DDDDDD).