James Dickens James Dickens - 4 months ago 8
Javascript Question

Including strings as parameters for a function chosen for .setAttribute to a button in javascript

I want to be able to pass along a string as a value for a button's onclick function using setAttribute. I am getting the error that "add is not defined" when I click on the button and I am not sure what I am doing wrong.

var AddButton = document.createElement("button");
var AddString = "add";
var SectorString = "1_1";
AddButton.setAttribute("onclick",'AddOrDeleteDiv(AddString,SectorString)');





function AddOrDeleteDiv(AddString, SectorString) {
//code
}

Answer

Do not use content attribute event handlers! Use event listeners instead:

var addButton = document.createElement("button");
var addString = "add";
var sectorString = "1_1";
addButton.addEventListener('click', function() {
  addOrDeleteDiv(addString, sectorString);
});
function addOrDeleteDiv(addString, sectorString) {
  //code 
}