user1834200
user1834200

Reputation: 162

Javascript - Listener executing on assignment

So, I'm currently working on a HTML page that displays a table with an editable text box and a delete button for the row for every quote in a list. The list is fetched from a stored file, so I need to dynamically generate this table and its rows every time I fetch it. However, when this code runs, the table generated is empty, because when the listener is added, the delete row function executes and just removes the row right after it's added.

    for (var i = 0; i < quotesArray.length; i++) {
      //Insert a new row into the table.
      var newQuoteRow = quoteList.insertRow(-1);
      var cellOne = newQuoteRow.insertCell(0);
      var cellTwo = newQuoteRow.insertCell(1);

      //Insert editable text boxes for a quote into the row.
      var quoteInput = document.createElement('input');
      quoteInput.value = quotesArray[i];
      quoteInput.className = "quote";
      cellOne.appendChild(quoteInput);

      //Put a delete button at the end of the row.
      var deleteQuoteButton = document.createElement('button');
      deleteQuoteButton.innerHTML = "x";
      cellTwo.appendChild(deleteQuoteButton);
      deleteQuoteButton.addEventListener('click', deleteCurrentQuoteRow(deleteQuoteButton));
    }


  });
}

function deleteCurrentQuoteRow(buttonToDelete) {
  var currentRow = buttonToDelete.parentNode.parentNode; //get the grandparent node, which is the row containing the cell containing the button.
  currentRow.parentNode.removeChild(currentRow); //delete the row in the table
}

From what I understand, this problem occurs because the function linked to in the addEventListener method has a parameter, which causes it to execute immediately instead of waiting for a click. However, I can't think of a way to implement this without passing the button being clicked as the parameter, because then I won't know which row to delete. How can I fix this so that the table will actually populate, and the delete button will actually delete a row?

Upvotes: 0

Views: 53

Answers (1)

Satpal
Satpal

Reputation: 133403

Currently you are invoking the function deleteCurrentQuoteRow and assigning its return value which is undefined as event listener.

Use

deleteQuoteButton.addEventListener('click', function(){
    deleteCurrentQuoteRow(this); //Here this refers to element which invoke the event
});

OR, You can modify the function deleteCurrentQuoteRow as

function deleteCurrentQuoteRow() {
  var currentRow = this.parentNode.parentNode; //get the grandparent node, which is the row containing the cell containing the button.
  currentRow.parentNode.removeChild(currentRow); //delete the row in the table
}

Then you can just pass the function reference as

deleteQuoteButton.addEventListener('click', deleteCurrentQuoteRow);

Upvotes: 1

Related Questions