1

I am new to Javascript. I am trying to create a unit conversion calculator. I want to loop through a table x and add an onclick that outputs the clicked buttons value.

I've been able to return a NodeList which I am looping through. After I add an onclick. Each button click 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>

If I click any button my output will be the value of the last button in the list (DDDDDD)

Vikram Deshmukh
  • 12,304
  • 4
  • 36
  • 38
JCK
  • 81
  • 3

1 Answers1

1

Variable b is being over written since its in the same code block. To get correct value use this.value instead of b.value. Avoid creating a function within a loop, overwriting variables. Use addeventlistener instead of onclick. var x = document.getElementsByName("Scalar")

var out = document.getElementById("output")

function Edit(){
    out.innerHTML = this.value
 }

for (i = 0; i < x.length; i++) {

   x[i].addEventListener( 'click' , Edit );

 }
  • Will read up about addEventListener and this, but it works! Thank you so much. Was driving me crazy, I can finish my assignment now :) – JCK Jun 06 '19 at 20:38