govinda
govinda

Reputation: 1693

clicking a child checkbox inside a parent li - the same as clicking adjacent text in the li

This must be quite simple (and probably a dupe), but I am not seeing it just now, and I have been looking!

I read (and attempted) more than just these approaches to my problem:

Click a li to check / uncheck a checkbox

Click a div to check / uncheck a checkbox

...but for the life of me, I seem unable to get the checkboxes in this fiddle:

http://jsfiddle.net/purushagovinda/7wZcS/8/

nor this SO-inspired derivative:

http://jsfiddle.net/purushagovinda/ysKLE/3/

...to behave as per my requirement:

I need that clicking on the text in a <li> will fire the toggle and highlight/un-highlight that text and check/uncheck that corresponding checkbox. Clicking on a checkbox itself should behave the exact same as if the user had clicked the adjacent text instead of the checkbox.

What happens now is that clicking the checkbox does nothing.
I have tried playing (in the first fiddle) with permutations and combinations of these lines:

if (target.is('input:checkbox')) return;

&

   //e.preventDefault();
   //e.stopPropagation();

..but to no avail.

If anyone has any guidance for me, I'd appreciate it.

---Edit:---

I should have mentioned that I need the toggle functions because I am doing a lot more stuff inside those functions that just toggling the font-weight and checking/unchecking the checkbox.

Upvotes: 2

Views: 1502

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206508

Tried different stuff and came up with this simple solution:

jsBin demo

CSS:

#products_furniture_finishes_options span{
  padding-left:28px;
  margin-left:-28px;  /* now cover the checkbox :) */
}

jQuery:

$("#products_furniture_finishes_options > li").click(function(){

  var isChecked = $(this).find('input').is(':checked'); // returns a BOOLEAN value

  $(this).find('span').css({fontWeight: isChecked ? '400' : '700' });
  $(this).find('input').prop('checked', !isChecked);

  if( isChecked ){

       // do WOW stuff here (if checkbox was already checked)

  }else{

       // do other COOL stuff (if checkbox was OFF)

  }


});

Upvotes: 3

Guffa
Guffa

Reputation: 700660

Put a label around the checkbox and the text, that will make clicking on the text activate the checkbox:

<label>
  <input type="checkbox" title="Mesh Back" name="products_furniture_finishes" value="13548454609475">
  <span>Mesh Back</span>
</label>

On the click event of the checkboxes, set the style of the list item depending on the state of the checkbox:

$("#products_furniture_finishes_options :checkbox").click(function(e) {
  var checked = $(this).is(':checked');
  var li = $(this).closest('li');
  li.css("font-weight", checked ? "700" : "400");
});

Demo: http://jsfiddle.net/Guffa/7wZcS/9/

Upvotes: 2

Related Questions