-2

Why does this not toggle correctly?

$('#violation_form label').click(function() {
    //alert($(this).parent().prev().html());
    var $checkbox = $(this).closest('li').find('input[type="checkbox"]');
    console.log(!$checkbox.attr('checked'));
    $checkbox.attr('checked', !$checkbox.attr('checked'));
});

http://jsfiddle.net/SEkTp/2/

George Newton
  • 3,153
  • 7
  • 34
  • 49

5 Answers5

2

You're misusing <label> element. There's no point doing magic tricks to make clicking it affect the corresponding <input> when you can do it directly. Quoting the docs (MDN):

The HTML <label> Element represents a caption for an item in a user interface. It can be associated with a control either by placing the control element inside the label element, or by using the for attribute. Such a control is called the labeled control of the label element.

So both...

<label><input type="checkbox" />Whatever</label>

... and, more complex, but more flexible:

<input type="checkbox" name="some_checkbox" id="some_checkbox" />
<label for="some_checkbox">Whatever it is</label>

... will work.

Demo.

raina77ow
  • 103,633
  • 15
  • 192
  • 229
1

There is no li element in the DOM. Also use prop to set checkboxes on/off. Try this:

    $('#violation_form label').click(function() {
    $checkbox = $(this).closest('form').find('input[type="checkbox"]');
    console.log(!$checkbox.attr('checked'));
    $checkbox.prop("checked", !$checkbox.prop("checked"));
});

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
1

You can use .prop() instead of .attr() to set the checked state of your checkbox:

$checkbox.prop('checked', !$checkbox.prop('checked'));

Final code look like:

$('#violation_form label').click(function () {
    //alert($(this).parent().prev().html());
    var $checkbox = $(this).closest('li').find('input[type="checkbox"]');
    console.log(!$checkbox.prop('checked'));
    $checkbox.prop('checked', !$checkbox.prop('checked'));
});

Updated Fiddle

Felix
  • 37,892
  • 8
  • 43
  • 55
1

Maybe you want this => http://jsfiddle.net/SEkTp/14/

jQuery('#violation_form label').click(function() {
   // alert("hi");
    //alert($(this).parent().prev().html());
    var checkbox = jQuery(this).find('input[type="checkbox"]');
    console.log(!checkbox.attr('checked'));
    checkbox.attr('checked', !checkbox.attr('checked'));
});
Pratik Joshi
  • 11,485
  • 7
  • 41
  • 73
1

Check this one, You missed <li> in that structure. Now it's working fine

Demo

Ravichandran Jothi
  • 3,028
  • 11
  • 52
  • 82