Prog Grl
Prog Grl

Reputation: 37

To assign onclick event to multiple buttons

I am working on a code to generate multiple buttons depending on user input

    for(var loop = 0; loop < up.length ; loop++){
document.write('<button style="background-color:'+ up[loop] +';width:100;height:100" </button>');

}

however I want to have same onclick function for every button,but if I use like the one below, the function doesn't gets executed . What's the problem and where am I going wrong? Please help.

document.write('<button style="background-color:'+ up[loop] +';width:100;height:100" onclick= "myfn()" </button>');

Upvotes: 2

Views: 3512

Answers (3)

m1.
m1.

Reputation: 1325

what about something like this (no jquery needed and no document.write):

var button;
for (i=0; i<5; i++) {
    button = document.createElement('button');
    button.innerHTML = "button - " + i;
    button.addEventListener('click', myFn);
    document.body.appendChild(button);
}


function myFn() {
    alert('button clicked');
}

see here: http://jsfiddle.net/yNFqy/1/

Upvotes: 0

almo
almo

Reputation: 6367

  1. Use jQuery
  2. Add a class to the buttons (always the same class)
  3. User jQuery's click method to handle the click

$('.class-name).click(function() { alert("click"); });

Upvotes: 0

Mister Epic
Mister Epic

Reputation: 16723

Typo, you don't close your opening tag:

 document.write('<button style="background-color:'+ up[loop] +';width:100;height:100" onclick="myfn()"></button>');

Always make sure you validate with the W3c markup validation service: http://validator.w3.org

You should also investigate unobtrusively attaching event handlers, writing handlers inline isn't ideal.

Upvotes: 1

Related Questions