Checking a Checkbox inside a List Item by Clicking the Parent or Child

It’s quite common to see list items <li> or table rows <tr><td> which contain a checkbox <input type=”checkbox”/>. Rather than the user having to be very precise and click/touch on the checkbox, it’s often preferable, especially on mobile devices, to be able to click/touch anywhere in the item or row.

This sounds simple but throws up a problem. If we have click events on the item/row and the checkbox then a click on the checkbox fires both events, checking and then unchecking the checkbox. Setting e.stopPropagation on the checkbox click event doesn’t seem to work.

There are 2 solutions. The first is arguably simpler and more semantic. Simply wrap the checkbox in a <label> tag and then change the label’s CSS so that it fills the list item or row.

If this isn’t an option then it can be handled in JavaScript.

See the Pen Checking Checkboxes by Clicking Parent List Item by Chris Smith (@chris22smith) on CodePen

The refers to the element that was clicked. If, within the list item click, the checkbox is not clicked then change the checked state.

About Chris Smith

Web developer specialising in frontend UI design @chris22smith
This entry was posted in click(), JavaScript, jQuery and tagged , , , , , , , , , . Bookmark the permalink.

One Response to Checking a Checkbox inside a List Item by Clicking the Parent or Child

  1. arjun says:

    Thanks for this tip. i though i should use some js libraries for this ! but it’s just javascript(jquery).

Comments are closed.