0

I am trying to pass the value of a button to a function when it is clicked. Because the buttons were created as a javascript element I'm not sure how to do it.

    methods:{
      createButtons() {
        
        var i;
        var rows =["9","8","7","6","5","4","3","2","1","0","•","="];
        var elDiv = document.getElementById("myDIV");
        for (i=0; i<12; i++){ 
          var btn = document.createElement("BUTTON");
          btn.value = i
          btn.style.height = "40px"
          btn.textContent = rows[i];
          btn.onclick = buttonvalue;
          elDiv.appendChild(btn);  
        }
        var pressedbutton = document.getElementById("calculate");
        pressedbutton.remove();
      },
    }
  }

function buttonvalue(i){
  alert(i);
}

1 Answer 1

1

This is an XY problem. Don't create DOM elements manually like this, that's what Vue is for.

But to answer your question, you can do something like this:

const captureI = i;
btn.onclick = () => buttonvalue(captureI);

I copied i into a new local variable because i changes value by the for loop.

Or you can just write the for loop like this instead:

for (let i = 0; i < 12; i++) {
  // ... omitted code ...
  btn.onclick = () => buttonvalue(i);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.