This is my function and it should change the onClick attribute of the HTML input, but if I use
document.getElementById(\'buttonLED\'+id).onclick = \"writeLED
The line onclick = writeLED(1,1)
means that you want to immediately execute the function writeLED(arg1, arg2) with arguments 1, 1 and assign the return value; you need to instead create a function that will execute with those arguments and assign that. The topmost answer gave one example - another is to use the bind() function like so:
var writeLEDWithSpecifiedArguments = writeLED.bind(this, 1,1);
document.getElementById('buttonLED'+id).onclick = writeLEDWithSpecifiedArguments;
You are not actually changing the function.
onClick
is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.
Another problem is your variable color
seems out of nowhere.
Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)
You want to do this - set a function that will be executed to respond to the onclick event:
document.getElementById('buttonLED'+id).onclick = function(){ writeLED(1,1); } ;
The things you are doing don't work because:
The onclick event handler expects to have a function, here you are assigning a string
document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)";
In this, you are assigning as the onclick event handler the result of executing the writeLED(1,1) function:
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
Another solution is to set the 'onclick' attribute to a function that returns your writeLED function.
document.getElementById('buttonLED'+id).onclick = function(){ return writeLED(1,1)};
This can also be useful for other cases when you create an element in JavaScript while it has not yet been drawn in the browser.
Using Jquery instead of Javascript,
use 'attr'
property instead of 'setAttribute'
like
$('buttonLED'+id).attr('onclick','writeLED(1,1)')
Well, just do this and your problem is solved :
document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')
Have a nice day XD