3

I have this check box:

<div class="OuterDiv">
   <div class="InnerDiv">
      <input type="checkbox" name="tie" value="tie">Error in tie score<br>
   </div>
</div>

I have this jquery to toggle the checkbox:

$(document).ready(function() {
   $('.OuterDiv').click(function() {
      if ($(this).find('input:checkbox').is(':checked')) { 
         $(this).find('input:checkbox').attr('checked',false);
      } else {
         $(this).find('input:checkbox').attr('checked',true);
      }
   });
});

This seems to work, to toggling the checkbox when clicking on the div. However when I click the checkbox itself, nothing happens and it does not toggle.

Matt Ball
  • 344,413
  • 96
  • 627
  • 693
Ramuk
  • 217
  • 1
  • 4
  • 9

3 Answers3

2

Without a <label> around the input (entire DIV is clickable) go for:

LIVE DEMO

$(document).ready(function() {

   $('.OuterDiv').click(function(e) {
     var $chkb = $(':checkbox', this)[0];
     if(e.target !== $chkb) $chkb.checked = !$chkb.checked; 
   });

});

(No JS:)
Else, if you just want the text next to the checkbox to be clickable:
LIVE DEMO

<div class="OuterDiv">
   <div class="InnerDiv">
     <label>
      <input type="checkbox" name="tie" value="tie">Error in tie score<br>
     </label>
   </div>
</div>
Roko C. Buljan
  • 180,066
  • 36
  • 283
  • 292
1

You need to stop the propagation of the event bubbling up from your checkbox using event.stopPropagation()

$('input[type=checkbox]').click(function(e){
    e.stopPropagation();
});
wirey00
  • 33,149
  • 7
  • 51
  • 64
0

You don't need to use jQuery for this. Just use label tag as below:

<div class="OuterDiv">
    <label>
        <input type="checkbox" name="tie" value="tie">Error in tie score
    </label>
</div>
Dhawal
  • 47
  • 3