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(1,1)";
it does not work at all, but if I use
document.getElementById('buttonLED'+id).onclick = writeLED(1,1);
the function executes by itself! Any ideas what code do I have to use to change the onCLick attribute WITHOUT executing the function, before the button is clicked?
Here is the full function, if it matters:
function showLED(id){ if(color == 0){ document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)"; document.getElementById('buttonLED'+id).value="light is on"; //document.getElementById('buttonLED'+id).disabled = false; }else{ document.getElementById('buttonLED'+id).onclick = "writeLED(1,0)"; document.getElementById('buttonLED'+id).value="light is off"; //document.getElementById('buttonLED'+id).disabled = false; } }
Note that the onclick attribute is purely JavaScript. The value it takes, which is the function you want to execute, says it all, as it is invoked right within the opening tag. In JavaScript, you invoke a function by calling its name, then you put a parenthesis after the function identifier (the name).
The onClick attribute is an event handler that instructs the browser to run a script when the visitor clicks a button.
Well, just do this and your problem is solved :
document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)')
Have a nice day XD
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With