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
ivanhalenAsked:
Who is Participating?
 
khan_webguruConnect With a Mentor Commented:
Hello Bro!

Use the following code

 
$('#press li').click(function(){
        
        var label = $(this).find(":first");
        var checkbox = $(label).children('input[type=checkbox]');
        if (checkbox.is(':checked')) {
            $(this).removeClass('selected');
            checkbox[0].checked = false;
        } else {
            $(this).addClass('selected');
            checkbox[0].checked = true;
        }
    })

Open in new window


Hope thats what you want.

Regards,

Asif Ahmed Khan
0
 
ivanhalenAuthor Commented:
Perfect, thanks!!! :-)
0
 
khan_webguruCommented:
My Pleasure :)
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.