Reputation: 37
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
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
Reputation: 6367
$('.class-name).click(function() { alert("click"); });
Upvotes: 0
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