tags:

views:

756

answers:

4

I'm wondering if there is a way in jQuery to check/uncheck a checkbox when someone clicks an entire div layer. Like having a massive selection area, essentially.

Any ideas?

Here is an example... I am trying to make the around the checkbox clickable to toggle the individual checkbox, pretty much.

<fieldset>
    <div>
        <input type="checkbox" id="Checkbox1" />
    </div>
    Person 1<br />
</fieldset>
<fieldset>
    <div >
        <input type="checkbox" id="Checkbox2" />
    </div>
    Person 2<br />
</fieldset>
A: 

Your check all checkbox:

<input type="checkbox" id="checkAll" /> Check All

And your JS code:

  $('#checkAll').click(function() {
        if($(this).attr('checked')) {
         $('input:checkbox').attr('checked', false);
        } else {
         $('input:checkbox').attr('checked', true);
        }
    });
eyazici
Er, I don't think that does what I'm trying to do. I only want to check one box at a time if a larger layer around it is clicked. Not all of them. If I use that as an ID, I can only put it on one checkbox.
Stacey
No, I'm sorry. This isn't what I'm trying to do.
Stacey
A: 
$(function() {
          $('#divId').toggle(
            function(event) {
              $('input[name=foo]').attr('checked', true);
            },
            function(event) {
              $('input[name=foo]').attr('checked', false);
            }
          );
      });
Aaron
This is close, but it still checks everything on the page. The contents are being generated from a database, and there are dozens on the same page.
Stacey
+1  A: 

Perhaps use the clicked div as the parent.

$(function() {
     $('#divId').toggle(
       function(event) {
         $(this).find('input').attr('checked', true);
       },
       function(event) {
         $(this).find('input').attr('checked', false);
       }
     );
 });

This should only check the boxes inside the #divId that's clicked.

Joel L
Yes! I believe that did it! Can I bother for any information on what is going on here so I can understand it better?
Stacey
It's the same as Aaron's response, but instead of a global $('input') ("find all inputs in the document"), I limit it to the div ("this") that was clicked ("find all inputs inside "the clicked div")
Joel L
+2  A: 
$('fieldset div').bind('click', function() {
    var checkbox = $(this).find(':checkbox');

    checkbox.attr('checked', !checkbox.attr('checked'));
});
Jordan Ryan Moore
This also worked. Thank you all so much! I'm learning more about jQuery with each new thing I get to try.
Stacey