user2187325
user2187325

Reputation: 191

check uncheck All checkboxes with another single checkbox use jquery

I use jquery-1.9.1.js In my html page, it works well for the first time.

just like http://jsfiddle.net/pzCcE/1/

Can somebody help me to improve it?

<table id="tab1">
    <input type="checkbox" name="checkAll" id="checkAll">全選
    <input type="checkbox" name="book" id="book" value="book1">book1
    <input type="checkbox" name="book" id="book" value="book2">book2
    <input type="checkbox" name="book" id="book" value="book3">book3
    <input type="checkbox" name="book" id="book" value="book4">book4
    <input type="checkbox" name="book" id="book" value="book5">book5</table>

$(function () {
    $("#tab1 #checkAll").click(function () {
        if ($("#tab1 #checkAll").is(':checked')) {
            $("#tab1 input[type=checkbox]").each(function () {
                $(this).attr("checked", true);
            });

        } else {
            $("#tab1 input[type=checkbox]").each(function () {
                $(this).attr("checked", false);
            });
        }
    });
});

Upvotes: 18

Views: 78644

Answers (10)

Maxence Cupper
Maxence Cupper

Reputation: 21

This one work for all checkbox lists. just add "check-all" to the input controlling that, which must have the same name

$(function() {
  $('.check-all').each(function(){
    var checkListName = $(this).attr('name');
    $(this).change(function(){
      //change all checkbox of the list checked status
      $('input[name="'+checkListName+'"]').prop('checked', $(this).prop('checked')); 
    });
    $('input[name="'+checkListName+'"]').change(function(){
      //change .check-all checkbox depending of the list checked status
      $('input[name="'+checkListName+'"].check-all').prop('checked', ($('input[name="'+checkListName+'"]:checked').not('.check-all').length == $('input[name="'+checkListName+'"]').not('.check-all').length));
    });
  });
});

Upvotes: 0

Suhaib Janjua
Suhaib Janjua

Reputation: 3574

As the OP requires to check uncheck all checkboxes on the basis of another checkbox id=全選.

The solution that @j08691 is provided above is good but it lacks one thing and that is, the solution doesn't uncheck the id=全選 checkbox when any other checkbox in the list goes unchecked.

So I propose a solution that checks/unchecks all the checkboxes on the basis of id=全選 checkbox and if any other checkbox is unchecked then checkbox id=全選 goes unchecked. And if user manually clicks on all the other check boxes then check box id=全選 should also be checked to reflect the relationship.

OP using the same id for multiple checkboxes which is against the rules of DOM. Element IDs should be unique within the entire document.


So the following code covers all the aspects of this kind of scenario.

HTML

<table>
    <tr>
        <td>
        <input type="checkbox" name="checkAll" id="checkAll">全選 (ALL)
        <input type="checkbox" name="book" id="book_1" value="book1">book1
        <input type="checkbox" name="book" id="book_2" value="book2">book2
        <input type="checkbox" name="book" id="book_3" value="book3">book3
        <input type="checkbox" name="book" id="book_4" value="book4">book4
        <input type="checkbox" name="book" id="book_5" value="book5">book5
        </td>
     </tr>
</table>

JQuery

$(document).ready(function() {

    $('#checkAll').click(function () {
        $('input:checkbox').not(this).prop('checked', this.checked);
    });

    $("[id*=book_]").change(function () {
        if ($('input[id*=book_][type=checkbox]:checked').length == $('input[id*=book_][type=checkbox]').length) {
            $('#checkAll').prop('checked', true);
        } else {
            $('#checkAll').prop('checked', false);
        }
    });

});

Description of attribute selector [name*="value"]

Selects elements that have the specified attribute with a value containing a given substring.

So $('#checkAll') returns me the parent checkbox only, on which I check/uncheck all checkboxes.

And $('[id$=book_]') returns me all the checkbox except the parent(全選) checkbox. Then on the basis of parent checkbox I check/uncheck all the other checkboxes.


I also checks the length of the checkboxes other then parent(全選) checkbox, If all the other checkboxes are check then I check the parent(全選) checkbox. So this is the way to cross check all possible condition and never misses any scenario.

Demo working JSFiddle here.

Upvotes: 3

azhar
azhar

Reputation: 380

`change click to ch  $("#checkAll").click(); to $("#checkAll").change();

> Blockquote

$(function () {
 $("#checkAll").change(function () {
  if ($("#checkAll").is(':checked')) {
   $(".book").prop("checked", true);
   } else {
   $(".book").prop("checked", false);
  }
 });
});`

Upvotes: 0

Hannes Ledl
Hannes Ledl

Reputation: 21

the fastest way. and save some lines

   $(".ulPymnt input[type=checkbox]").each(function(){                
       $(this).prop("checked", !$(this).prop("checked"))                
   })

Upvotes: 2

Didac Montero
Didac Montero

Reputation: 2086

I've just simplified @j08691 answer

$("#checkAll").click(function() {
      var allChecked = $(this);
      $("#tab1 input[type=checkbox]").each(function() {
        $(this).prop("checked", allChecked.is(':checked'));
      })
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="tab1">
  <tr>
    <td>
      <input type="checkbox" name="checkAll" id="checkAll">Select all
      <input type="checkbox" name="book" id="book" value="book1">book1
      <input type="checkbox" name="book" id="book" value="book2">book2
      <input type="checkbox" name="book" id="book" value="book3">book3
    </td>
  </tr>
</table>

Upvotes: 1

Thomas Wood
Thomas Wood

Reputation: 819

$("input[name='select_all_photos']").click(function () {
        var checked = $(this).is(':checked');
        $("input[name^='delete_']").each(function () {
            $(this).prop("checked", checked);
        });
    });

Don't bother doing an if statement.

Upvotes: 0

Thivya
Thivya

Reputation: 3062

Add this too....FOR..... if one checkbox (id:book) is unselected means it will cause the main check box (id:checkAll) to be unselected

$("#tab1 #book").click(function () {
  if($('#book').is(':checked'))
  {
    $("#checkAll").prop("checked", false);        
  }
});

Upvotes: 0

j08691
j08691

Reputation: 207861

Change

$(this).attr("checked", true);

to

$(this).prop("checked", true);

jsFiddle example

I actually just answered another question that was similar to this. Per the .prop() docs:

The .prop() method is a convenient way to set the value of properties—especially when setting multiple properties, using values returned by a function, or setting values on multiple elements at once. It should be used when setting selectedIndex, tagName, nodeName, nodeType, ownerDocument, defaultChecked, or defaultSelected. Since jQuery 1.6, these properties can no longer be set with the .attr() method. They do not have corresponding attributes and are only properties.

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method. The .val() method should be used for getting and setting value.

Upvotes: 41

sasi
sasi

Reputation: 4318

With answer of j08691 look into following thing also..

It totally makes no sense to create a selector like #id #id because an ID has to be unique within your DOM by definition.

<input type="checkbox" name="checkAll" class="checkAll">

$("#tab1 .checkAll").click(function () {

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You should be using classes with the same name, ID's MUST be unique!

<input type="checkbox" name="checkAll" id="checkAll">全選
<input type="checkbox" name="book" class="book" value="book1">book1
<input type="checkbox" name="book" class="book" value="book2">book2
<input type="checkbox" name="book" class="book" value="book3">book3
<input type="checkbox" name="book" class="book" value="book4">book4
<input type="checkbox" name="book" class="book" value="book5">book5</table>

$(function () {
    $("#checkAll").click(function () {
        if ($("#checkAll").is(':checked')) {
            $(".book").prop("checked", true);
        } else {
            $(".book").prop("checked", false);
        }
    });
});

Upvotes: 10

Related Questions