4

I have a <div> with an onclick event and <checkbox>, <span> and <img> inside it.
When I click on the checkbox then the div-onclick event doesn't fire - I would like it to fire without having to duplicate the onclick onto the checkbox.

<div id="id-tag" onclick="do()">
  <span>text</span>
  <img src="pic.jpg" />
  <input type="checkbox" name="mycheck" />
</div>

I know the div-idtag but ideally would like to avoid specifying it inside the checkbox.
Using another function call on the checkbox onclick to call the parent is NOT what I am looking for, like

onclick="run_parent_onclick()"

but this is okay (untested):

onclick="this.parent.click()"

2 Answers 2

2

You could fire the div's click event manually in the input's onclick:

<input type="checkbox" name="mycheck" onclick="this.parentNode.click()" />

or

<input type="checkbox" name="mycheck" onclick="document.getElementById('id-tag').click()" />
2
  • Both work, but only if the checkbox is NOT disabled and I was having mine as disabled to control the checkedstate as the div onclick function can be cancel which means a user is able to check the box and cancel the function while the checkbox remained checked. Guess I have to think of something else to prevent this.
    – Kim
    May 4, 2010 at 14:01
  • Be aware that DOM .click() only works on some elements in Safari.
    – Alex W
    Jun 27, 2014 at 20:11
1

Use addEventListener:

function do(e) { ... }
document.getElementById('id-tag').addEventListener('click', do, true);

The "true" makes the event capture.

1
  • 1
    How does that bind the checkbox onclick event to the parent div onclick action ? Also I got hundreds to thousands of such divs, which why I am looking for something "global" as my untested example.
    – Kim
    May 3, 2010 at 10:47

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.