1

Hello people of the internet, I have a set of buttons and if a button is clicked it's content should be appended to a text field's content.

Lets say I have three buttons: [first] [second] [third] My addEventListener-implementation results in "third" appended to the in text field's content, regardless which button I press. I don't know hot to fix this.

function setupListeners() {
    var targetInputField = d.querySelector("#expression");
    var t = d.querySelectorAll(".expression-button").length;
    for (var i = 1; i <= t; i++) {
        var btnElem = d.querySelector("#expression-button-"+i);
        btnElem.addEventListener('click', function() {
            if (targetInputField.value == "") {
                targetInputField.value = btnElemLocal.innerText;
            }
            else {
                targetInputField.value += ";"+btnElemLocal.innerText;
            }
        });
    }
}

What I want:

If I click all of the three buttons in a row, the text field's content should be :

"first;second;third"

And not :

"third;third;third"

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
phip1611
  • 5,460
  • 4
  • 30
  • 57

1 Answers1

0

Put the click event code inside another function (btnClick in my example) and just call it when you attach the event in .addEventListener() inside the loop, then use this to refer to the current clicked element :

function btnClick() {
  var targetInputField = d.querySelector("#expression");

  if (targetInputField.value == "") {
    targetInputField.value = this.innerText;
  }
  else {
    targetInputField.value += ";"+this.innerText;
  }
}

Hope this helps.

var d = document;

function setupListeners() {      
  var t = d.querySelectorAll(".expression-button").length;

  for (var i = 1; i <= t; i++) {
    var btnElem = d.querySelector("#expression-button-"+i);
    
    btnElem.addEventListener('click', btnClick);
  }
}

function btnClick() {
  var targetInputField = d.querySelector("#expression");
  
  if (targetInputField.value == "") {
    targetInputField.value = this.innerText;
  }
  else {
    targetInputField.value += ";"+this.innerText;
  }
}

setupListeners();
<button class='expression-button' id='expression-button-1'>First</button>
<button class='expression-button' id='expression-button-2'>Second</button>
<button class='expression-button' id='expression-button-3'>Third</button>

<input id='expression' />
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101