2

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>');
1
  • Valid HTML is a prerequisite to get anything working, and using some sort of DOM insertion instead of document.write is always a good idea. Commented Nov 14, 2013 at 19:58

3 Answers 3

1

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.

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

Comments

0

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/

3 Comments

It worked! thanks,but how can I modify the look and feel of the button using css?
Yes, you can add a line there: button.classList.add('your-classname-here') and then style it w/ CSS
well, my function myFn() needs element at 'i' th position,like up[i],how can I pass an argument to myFn() here?
0
  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"); });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.