Home > Enterprise >  Trying to add onclick function to a button created in Javascript
Trying to add onclick function to a button created in Javascript

Time:08-19

I have a button created through javascript but I can't assign the function to the button.

The function works when I make it an onclick not assigned to any button so I know I'm probably formatting something wrong.

Any help is appreciated.

JS code

var tickButton;
for (tickButton = 0; tickButton < myNodelist.length; tickButton  ) {
  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u2713");
  span.className = "tick";
  span.appendChild(txt);

  tickButton.onclick = function(){
    alert('hello');
  };

  myNodelist[tickButton].appendChild(span);
}

CodePudding user response:

I guess you can use this code :

let btn = document.createElement("button");
btn.innerHTML = "Save";
btn.onclick = function () {
  alert("Button is clicked");
};
document.body.appendChild(btn);

or

let btn = document.createElement("button");
btn.innerHTML = "Save";
btn.addEventListener("click", function () {
  alert("Button is clicked");
});
document.body.appendChild(btn);

But I suggest using onClick, it's a better way to do it. Also, be aware that you should add the whole code in your loop. Since you must not be looping on the variable that contain the button.

Source : https://sebhastian.com/javascript-create-button/

CodePudding user response:

You are adding the onclick to your iterator. Add it to your span instead:

var tickButton;
var myNodelist = document.querySelectorAll('#crudList li');
for (tickButton = 0; tickButton < myNodelist.length; tickButton  ) {

  var span = document.createElement("SPAN");
  var txt = document.createTextNode("\u2713");
  
  span.className = "tick";
  span.appendChild(txt);

  span.addEventListener(
    "click",
    function(){
      alert('hello');
    }
   );
  myNodelist[tickButton].appendChild(span);
}
<ul id="crudList">
<li>1</li>
<li>2</li>
<li>3</li>
</ul>

  • Related