1

I've got a quick question: I've got a function that stores id's in an array called "view1". When a certain requirement is met, I want these id's onclick to change. I want them to load a function called clickMem(id) when they are clicked, and also send in their id in the function. So I've tried this with the first id in the array and it didn't work, what am I doing wrong?

document.getElementById(view1[0]).onclick='clickMem('+view1[0]+');';

Thank you in advance!

3
  • onclick expects a function, not a string. See developer.mozilla.org/en-US/docs/Web/API/… Commented Apr 12, 2014 at 17:17
  • Setting the onclick event will do nothing but bind a function to the event. The event needs to be triggered for something to happen. From reading your question, it sounds like you want the function to run when the condition is met, not just bind the function and do nothing. Am I right? Commented Apr 12, 2014 at 17:27
  • Oh, no, I just want to bind the function to the id. I don't want it to run until the div with the id is clicked. And I'm afraid the answers below doesn't seem to work for me... Commented Apr 12, 2014 at 21:41

2 Answers 2

1

Use setAttribute :

  var new_onclick = 'clickMem('+view1[0]+')';
  document.getElementById(view1[0]).setAttribute('onclick',new_onclick);

But Note:

document.getElementById('buttonLED'+id).onclick = clickMem(view1[0]); 

Sets the onclick property of the element to the result of clickMem(view1[0]) as it would call that function and assign the value returned by that function to the onclick property, which is something you don't want.

So pass a function(){clickMem(view1[0]);}

document.getElementById('buttonLED'+id).onclick = function(){clickMem(view1[0]);}

which can also work .

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

8 Comments

why not document.getElementById(view1[0]).onclick=clickMem(view1[0]);?
@vivek_nk: That would execute clickMem immediately, not when the click event is triggered.
@Aditya: The result your .onclick solution is different from your setAttribute solution.
Yes i meant BUT not OR, updated answer and thanks a ton for pointing out there
I don't think "BUT" makes it clear enough what the difference is. Instead of writing a comment, I'd suggest to properly write two or three sentences about the differences, and really make clear that those are two different solutions. Why are suggestion two different solutions anyway?
|
0

Try this:

document.getElementById(view1[0]).onclick=function() {clickMem(view1[0]);}

1 Comment

You are assuming that clickMem returns a function, which it might not do.

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.