jquery select all checkboxes

Viewed 90659

I have a series of checkboxes that are loaded 100 at a time via ajax.

I need this jquery to allow me to have a button when pushed check all on screen. If more are loaded, and the button is pressed, to perhaps toggle all off, then pressed again toggle all back on.

This is what i have, obviously its not working for me.

$(function () {
 $('#selectall').click(function () {
  $('#friendslist').find(':checkbox').attr('checked', this.checked);
 });
});

The button is #selectall, the check boxes are class .tf, and they all reside in a parent div called #check, inside a div called #friend, inside a div called #friendslist

Example:

<div id='friendslist'>
    <div id='friend'>
        <div id='check'>
            <input type='checkbox' class='tf' name='hurr' value='durr1'>
        </div>
    </div>
    <div id='friend'>
        <div id='check'>
            <input type='checkbox' class='tf' name='hurr' value='durr2'>
        </div>
    </div>
    <div id='friend'>
        <div id='check'>
            <input type='checkbox' class='tf' name='hurr' value='durr3'>
        </div>
    </div>
</div>

<input type='button' id='selectall' value="Select All">
19 Answers

Use the jquery toggle function. Then you can also perform whatever other changes you may want to do along with those changes... such as changing the value of the button to say "check all" or "uncheck all".

$(function () {
    $('#selectall').toggle(
        function() {
            $('#friendslist .tf').attr('checked', 'checked');
        },
        function() {
            $('#friendslist .tf').attr('checked', '');
        }
    );
});

So "checked" is a crappy attribute; in many browsers it doesn't work as expected :-( Try doing:

$('#friendslist').find(':checkbox')
    .attr('checked', this.checked)
    .attr('defaultChecked', this.checked);

I know setting "defaultChecked" doesn't make any sense, but try it and see if it helps.

It works for me (IE, Safari, Firefox) by just changing your this.checked to 'checked'.

$(function() {
  $('#selectall').click(function() {
    $('#friendslist').find(':checkbox').attr('checked', 'checked');
  });
 });

You may try this:

$(function () {
 $('#selectall').click(function () {
  $('#friendslist input:checkbox').attr('checked', checked_status);
 });
});

//checked_status=true/false -as the case may be, or set it via a variable

assuming #selectall is a checkbox itself whose state you want copied to all the other checkboxes?

$(function () {
 $('#selectall').click(function () {
  $('#friendslist input:checkbox').attr('checked', $(this).attr('checked'));
 });
});
Related