Link to home
Start Free TrialLog in
Avatar of ivanhalen
ivanhalenFlag for Italy

asked on

Toggle checkbox when clicking on a li (and toggling a class) with jQuery

Hello,
I have this HTML:
<ul id="press">
  <li class="selected">
    <label>
      <input name="ip_press[]" type="checkbox" value="1" checked="checked"  />
      <strong>First text</strong></label>
    <div>27/03/2011</div>
  </li>
  <li>
    <label>
      <input name="ip_press[]" type="checkbox" value="2"  />
      <strong>Other text</strong></label>
    <div>23/03/2011</div>
  </li>
  <li class="selected">
    <label>
      <input name="ip_press[]" type="checkbox" value="4" checked="checked"  />
      <strong>Another text</strong></label>
    <div>17/03/2011</div>
  </li>
</ul>

Open in new window

And this jQuery snippet:
$('#press li label').click(function(){
	var checkbox = $(this).children('input[type=checkbox]');
	if (checkbox.is(':checked')) {
		$(this).parent('li').addClass('selected');
	} else {
		$(this).parent('li').removeClass('selected');
	}
})

Open in new window


All is fine: when I click on the <label>, che corresponding checkbox is toggled and the class "selected" too
But what if I want to click on the whole <li> to toggle the checkbox and the class?

Here's a live example:
http://jsfiddle.net/TeWsw/2/

Thanks in advance for your help
ASKER CERTIFIED SOLUTION
Avatar of khan_webguru
khan_webguru
Flag of Australia image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ivanhalen

ASKER

Perfect, thanks!!! :-)
My Pleasure :)