met.lord
met.lord

Reputation: 618

CoffeeScript Nested Checkboxes

I have a sidebar with sections, within each section there are chapters, and within them, there are subchapters. Chapters and subchapters are marked as read with using checkboxes. What I'm trying to do is:

  1. Whenever I mark as checked a chapter checkbox, put a line through its label and all subchapters checkboxes get checked as well also with a line through.

  2. Whenever I unmark a chapter checkbox, the line-through disappears and all the subchapter checkboxes are unmarked as well as their line-throughs disappear.

I've been trying to get this to work for a while but without success, any help would be appreciated. Thanks.

$(".chapter-ended").live "change", ->
  id = $(this).attr("id")
  isChecked = $(this).attr("checked")
  if(isChecked)
    $(this).closest('li').css "text-decoration", "line-through"
  else
    $(this).closest('li').css "text-decoration", "none"


$(".subchapter-ended").live "change", ->
  id = $(this).attr("id")
  isChecked = $(this).attr("checked")
  if(isChecked)
    $(this).closest('li').css "text-decoration", "line-through"
  else
    $(this).closest('li').css "text-decoration", "none"

http://jsfiddle.net/MWHML/1/

Upvotes: 1

Views: 1214

Answers (1)

Stuart M
Stuart M

Reputation: 11588

I got this working using the following:

$(".chapter-ended").on "change", ->
  isChecked = $(this).is(':checked')
  $(this).closest('li').find('li input[type="checkbox"]').prop('checked', isChecked);
  if(isChecked)
    $(this).closest('li').css "text-decoration", "line-through"
  else
    $(this).closest('li').css "text-decoration", "none"


$(".subchapter-ended").on "change", ->
  isChecked = $(this).is(':checked')
  $(this).closest('li').find('li input[type="checkbox"]').prop('checked', isChecked);
  if(isChecked)
    $(this).closest('li').css "text-decoration", "line-through"
  else
    $(this).closest('li').css "text-decoration", "none"

I made the following changes:

  • .on() instead of .live() for the event handler
  • .is(':checked') instead of .attr('checked') to see if the checkbox is checked
  • Find all child checkbox inputs and mark them as checked, using .prop('checked', isChecked)
  • removed id variable since I didn't see it being used anywhere

Upvotes: 3

Related Questions