0

I need to create a button in a loop dynamically and attach "onclick" event handler to it and then function for the handler is pre-defined and accepts multiple arguments.

for (var i = 0; .....) {
  var b = document.createElement("BUTTON");
  b.appendChild(document.createTextNode("fdsfdsfd_" + i)); 
  b.onclick = function() {
    var b = getB();
    var c = getC();
    myFunction(i, b, c);
  };

  document.appendChild(b);
}



function myFunction(a, b, c) {

}

But when I inspect the thml, there's no "onclick" attribute.

The property innerHTML doesn't fit for my case.

2 Answers 2

1

try this

var b = document.createElement("BUTTON");
b.appendChild(document.createTextNode("fdsfdsfd_" + i)); 
b.addEventListener('click', function() {
  console.log('anchor');
});

and onclick attribute is not necessary for click event to work

Sign up to request clarification or add additional context in comments.

2 Comments

and what's necessary?.
@Mook binding an event is necessary for a click event to work, and binding can be done via 'addEventListener' or via onclick. So 'onclick' is not the only way to set a click event.
0

$('#Delta1').click(function() {
  var functions = ['btn1()', 'btn2()', 'btn3()', 'btn4()', 'btn5()', 'btn6()', 'btn7()', 'btn8()', 'btn9()', 'btn10()'];
  var div = document.getElementById('insertHere');
  var ctr = 1;
  for (var i in functions) {

    var btn = document.createElement('button');
    var txt = document.createTextNode(String(ctr));

    btn.appendChild(txt);
    btn.setAttribute('type', 'button');
    btn.setAttribute('onclick', functions[i]);
    btn.setAttribute('id', 'button' + ctr);
    div.appendChild(btn);
    ctr++;
  }
});

function btn1() {
  alert('button 1');
}

function btn2() {
  alert('button 2');
}

function btn3() {
  alert('button 3');
}

function btn4() {
  alert('button 4');
}

function btn5() {
  alert('button 5');
}

function btn6() {
  alert('button 6');
}

function btn7() {
  alert('button 7');
}

function btn8() {
  alert('button 8');
}

function btn9() {
  alert('button 9');
}

function btn10() {
  alert('button 10');
}
<button type="button" id="Delta1">Blast Off!</button>
<div id="insertHere"></div>

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.