Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change onClick attribute with javascript

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;     } } 
like image 473
shiro Avatar asked Feb 26 '13 19:02

shiro


People also ask

Is onclick HTML or JavaScript?

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).

What does the onclick attribute do?

The onClick attribute is an event handler that instructs the browser to run a script when the visitor clicks a button.


Video Answer


2 Answers

Well, just do this and your problem is solved :

document.getElementById('buttonLED'+id).setAttribute('onclick','writeLED(1,1)') 

Have a nice day XD

like image 156
Marcelo Teixeira Ruggeri Avatar answered Oct 14 '22 12:10

Marcelo Teixeira Ruggeri


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:

  1. The onclick event handler expects to have a function, here you are assigning a string

    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)"; 
  2. 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); 
like image 42
DanC Avatar answered Oct 14 '22 12:10

DanC