0

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);
}
GagGreene
  • 1
  • 2
  • Are there any errors in your console? What is `myNodelist`? That doesn't seem to actually append the span to the document. – mykaf Aug 18 '22 at 14:15
  • @user1599011 No errors in the console. `myNodelist` is the variable that assigns the button created to list items in HTML. `var myNodelist = document.querySelectorAll('#crudList li')` – GagGreene Aug 18 '22 at 15:10
  • You should include your html for a more comprehensive example. – mykaf Aug 18 '22 at 15:29
  • Here's the relevant HTML `
    • Hit the gym
    • Pay bills
    • Meet George
    • Buy eggs
    • Read a book
    • Organize office
    `
    – GagGreene Aug 18 '22 at 15:41

2 Answers2

1

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>
mykaf
  • 1,034
  • 1
  • 9
  • 12
-1

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/

Weac
  • 124
  • 9
  • 2
    "But I suggest using onClick, it's a better way to do it." Based on what? – duckdotexe Aug 18 '22 at 14:32
  • I were wrong about this part : https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick It's mostly depending on what you're doing – Weac Aug 18 '22 at 14:41