62

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;
    }
}
3
  • 3
    document.getElementById('buttonLED'+id).onclick = "writeLED(1,1)"; is setting the onclick property of the element to a string.
    – crush
    Commented Feb 26, 2013 at 19:13
  • 2
    document.getElementById('buttonLED'+id).onclick = writeLED(1,1); is setting the onclick property of the element to the result of writeLED(1,1)
    – crush
    Commented Feb 26, 2013 at 19:14
  • 1
    Possible duplicate of Change onclick action with a Javascript function
    – Vadzim
    Commented Dec 8, 2016 at 15:06

7 Answers 7

118

Well, just do this and your problem is solved :

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

Have a nice day XD

4
  • 2
    thnx a lot. that is exactly the behavior I wanted.
    – Rusty
    Commented Jul 3, 2015 at 7:47
  • 3
    This seems like the answer to the actual question, rather than just a kludge to get something working. Commented May 16, 2016 at 14:27
  • 2
    You just solved my problem after searching for a solution for hours! :) Thank you!!!
    – DanielaB67
    Commented May 20, 2018 at 22:42
  • 2
    As of today, "The addEventListener() method is the recommended way to register an event listener" – MDN Web Docs. So, should it be document.getElementById('buttonLED'+id).addEventListener('onclick', writeLED.bind([1,1])) ? (Reference) Commented Nov 6, 2021 at 2:26
53

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);
    
2
  • 3
    +1 "when you have a problem - add another layer of abstraction" - classic :)
    – Nir Alfasi
    Commented Feb 26, 2013 at 19:14
  • 2
    Oh I hate that. If you inspect the buttonLED element, you'll see that the onclick attribute is not being set, it's creating an ephemeral event handler that you won't be able to see in the source. Marcelo Teixeira Ruggeri's answer below actually SETS the onclick attribute, which is what the original question asked. I won't downvote this answer because it works and was accepted, but to me, it sure does stink. Commented May 16, 2016 at 14:25
3

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;
1

Using Jquery instead of Javascript, use 'attr' property instead of 'setAttribute'

like

$('buttonLED'+id).attr('onclick','writeLED(1,1)')
0
0

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)

0

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.

1
  • This doesn't work if element is not yet drawn. To make it works if elements is not yet drawn, you need wo add another level of abstraction and use "addEventListener": document.addEventListener('click', document.getElementById('buttonLED'+id), function(){ return writeLED(1,1)}); Commented Sep 22, 2021 at 6:19
-1

First we'll select the required button using query selector and for all the selected buttons we'll set the onclick attribute with a function that needs to be called by clicking on the buttons. You can write the code for required work you want to do by clicking the button in the function defined.

Well "One of the" generalized solution to your to your problem can be achieved by the following code:

var a=document.querySelectorAll('button');


for(b=0;b<a.length;b++)
   {   
        a[b].setAttribute("onclick","check("+b+")");
   }
  function check(e)
   {    
    var sa=a[e].innerHTML;
    console.log('working onclick',sa);
   }
1
  • 1
    Code-only answers are considered low quality. Without sufficient explanation, your answer is hard to understand. If the OP can't understand your answer, then he also won't be able to reproduce your possible solution. As such it would be worthless to him/her. Please add a sufficient explanation of your possible solution.
    – tacoshy
    Commented Jul 6, 2022 at 21:19

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.