2

How can I dynamically create HTML buttons, in Javascript, that when users click on them they call a same function, but with a different parameters. For example:

function a(param){console.log(param);};

for (int i = 0; i < 10; i++)
{
   button = document.createElement('button');
   button.onclick = <place a function that when button is clicked, calls function a with parameter i>;
}

Can someone give me a clue?

2 Answers 2

2

Call the a function:

button.setAttribute('data-param', i);
button.onclick = function () {a(this.getAttribute('data-param'));};     

jsFiddle: http://jsfiddle.net/systemovich/asw3myqg/1/

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

1 Comment

@Fernando, fixed. Checkout the jsFiddle.
0
function b(param){
    var myParam = param;
    return function a() {
         console.log(myParam);
    }
}
for (int i = 0; i < 10; i++)
{
   button = document.createElement('button');
   button.onclick = b(i);
}

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.