0

I have this HTML code

<div class="friends_container">
   <div class="friend">
       <input type="checkbox" />    
      ...
   </div>
<div class="friend">
       <input type="checkbox" />    
      ...
   </div>
<div class="friend">
       <input type="checkbox" />    
      ...
   </div>
</div>

with select all/ unselect all link

<a id="selectall" href="#" >select all</a>

I tried to make it work, but I failed.. any help?

JsFiddle Here

Danubian Sailor
  • 1
  • 38
  • 145
  • 223
Dot Freelancer
  • 4,083
  • 3
  • 28
  • 50
  • 4
    There are _n_ questions about checking/unchecking checkboxes on SO. Isn't that enough? – Ram Sep 05 '13 at 11:19

6 Answers6

2

with changing your link to checkbox, it will be easy

try this

<input id="selectall" type="checkbox"  />select all

js

 $('#selectall').click(function(){
    $('.friend').find('input:checkbox').prop('checked',this.checked);
})

fiddle here


with a link

$('#selectall').click(function(){
    $('.friend').find('input:checkbox').prop('checked',true);
})

create one more link to unselect the checkbox

bipen
  • 36,319
  • 9
  • 49
  • 62
1

To check -

$("input[type='checkbox']").prop('checked', true);

To uncheck -

$("input[type='checkbox']").prop('checked', false);

Doing it using an anchor -

$("#selectall").click(function(){
   $("input[type='checkbox']").prop('checked', true);
});

And also if you have some anchor for deselecting -

<a id="deselectall" href="#" >deselect all</a>

you can add deselect all listener to it -

$("#deselectall").click(function(){
   $("input[type='checkbox']").prop('checked', false);
});
Moazzam Khan
  • 3,130
  • 2
  • 20
  • 35
1

You can use jQuery .prop() method for this purpose.

$(function() {
    var $checkboxes = $('.friends_container>.friend>input:checkbox');
    $('#selectall').on('click', function(e) {
        e.preventDefault();
        $(this).toggleClass('selected');
        $checkboxes.prop('checked', function() {
            return !this.checked;
        });
    });
});

DEMO

Eugene Naydenov
  • 7,165
  • 2
  • 25
  • 43
0
//checkall
$('#selectall').on('click', function (e) {
    $('input[type="checkbox"]').prop('checked', true);
    e.preventDefault();
});
//uncheck all
$('#unselectall').on('click', function (e) {
    $('input[type="checkbox"]').prop('checked', false);
    e.preventDefault();
});
Anton
  • 32,245
  • 5
  • 44
  • 54
0
$('#selectall').click(function(e){
  e.preventDefault();
  $('input[type="checkbox"]').prop('checked',this.checked);
});
Dipesh Parmar
  • 27,090
  • 8
  • 61
  • 90
0

jquery version 1.6 + use prop

$("#input[type='checked']").prop('checked',true);

jquery version 1.6 - use attr

$("#input[type='checked']").attr('checked','checked');

or

$("#input[type='checked']").attr('checked',true);
Somnath Kharat
  • 3,570
  • 2
  • 27
  • 51