开发者

How do I check/uncheck all checkboxes with a button using jQuery?

I am trying to check/uncheck all checkboxes using jQuery. Now by checking/unchecking the parent checkbox all the child checkboxes are getting selected/deselected also with the text of parent checkbox getting changed to checkall/uncheckall.

Now I want to replace parent checkbox with an input button, and change the text also on the button to checkall/uncheckall. THere is the code, can anyone please tweak the code ?

    $( function() {
        $( '.checkAll' ).live( 'change', function() {
            $( '.cb-element' ).attr( 'checked', $( this ).is( ':che开发者_如何转开发cked' ) ? 'checked' : '' );
            $( this ).next().text( $( this ).is( ':checked' ) ? 'Uncheck All' : 'Check All' );
        });
        $( '.cb-element' ).live( 'change', function() {
            $( '.cb-element' ).length == $( '.cb-element:checked' ).length ? $( '.checkAll' ).attr( 'checked', 'checked' ).next().text( 'Uncheck All' ) : $( '.checkAll' ).attr( 'checked', '' ).next().text( 'Check All' );

        });
    });


   <input type="checkbox" class="checkAll" /> <b>Check All</b>

   <input type="checkbox" class="cb-element" /> Checkbox  1
   <input type="checkbox" class="cb-element" /> Checkbox  2
   <input type="checkbox" class="cb-element" /> Checkbox  3


Try this one :

$(document).ready(function(){
    $('.check:button').toggle(function(){
        $('input:checkbox').attr('checked','checked');
        $(this).val('uncheck all');
    },function(){
        $('input:checkbox').removeAttr('checked');
        $(this).val('check all');        
    })
})

DEMO


This is the shortest way I've found (needs jQuery1.6+)

HTML:

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

JS:

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

I'm using .prop as .attr doesn't work for checkboxes in jQuery 1.6+ unless you've explicitly added a checked attribute to your input tag.

Example-

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
    
    <fieldset>
        <legend>Loads of checkboxes</legend>
        <p><label><input type="checkbox" /> Option 1</label></p>
        <p><label><input type="checkbox" /> Option 2</label></p>
        <p><label><input type="checkbox" /> Option 3</label></p>
        <p><label><input type="checkbox" /> Option 4</label></p>
    </fieldset>
</form>


Try This One:

HTML

<input type="checkbox" name="all" id="checkall" />

JavaScript

$('#checkall:checkbox').change(function () {
   if($(this).attr("checked")) $('input:checkbox').attr('checked','checked');
   else $('input:checkbox').removeAttr('checked');
});​

DEMO


Html

<input type="checkbox" name="select_all" id="select_all" class="checkAll" />

Javascript

    $('.checkAll').click(function(){
    if($(this).attr('checked')){
        $('input:checkbox').attr('checked',true);
    }
    else{
        $('input:checkbox').attr('checked',false);
    }
});


Try this:

$('.checkAll').on('click', function(e) {
     $('.cb-element').prop('checked', $(e.target).prop('checked'));
});

e is the event generated when you do click, and e.target is the element clicked (.checkAll), so you only have to put the property checked of elements with class .cb-element like that of element with class .checkAll`.

PS: Excuse my bad English!


Check / Uncheck All with Intermediate property using jQuery

Get Checked Items in Array using getSelectedItems() method

Source Checkbox List Select / Unselect All with Indeterminate Master Check

How do I check/uncheck all checkboxes with a button using jQuery?

HTML

<div class="container">
  <div class="card">
    <div class="card-header">
      <ul class="list-group list-group-flush">
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="selectAll"
            id="masterCheck"
          />
          <label class="form-check-label" for="masterCheck">
            Select / Unselect All
          </label>
        </li>
      </ul>
    </div>
    <div class="card-body">
      <ul class="list-group list-group-flush" id="list-wrapper">
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item1"
            id="item1"
          />
          <label class="form-check-label" for="item1">
            Item 1
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item2"
            id="item2"
          />
          <label class="form-check-label" for="item2">
            Item 2
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item3"
            id="item3"
          />
          <label class="form-check-label" for="item3">
            Item 3
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item4"
            id="item4"
          />
          <label class="form-check-label" for="item4">
            Item 4
          </label>
        </li>
        <li class="list-group-item">
          <input
            class="form-check-input"
            type="checkbox"
            value="item5"
            id="item5"
          />
          <label class="form-check-label" for="item5">
            Item 5
          </label>
        </li>
        <li class="list-group-item" id="selected-values"></li>
      </ul>
    </div>
  </div>
</div>

jQuery

  $(function() {
    // ID selector on Master Checkbox
    var masterCheck = $("#masterCheck");
    // ID selector on Items Container
    var listCheckItems = $("#list-wrapper :checkbox");

    // Click Event on Master Check
    masterCheck.on("click", function() {
      var isMasterChecked = $(this).is(":checked");
      listCheckItems.prop("checked", isMasterChecked);
      getSelectedItems();
    });

    // Change Event on each item checkbox
    listCheckItems.on("change", function() {
      // Total Checkboxes in list
      var totalItems = listCheckItems.length;
      // Total Checked Checkboxes in list
      var checkedItems = listCheckItems.filter(":checked").length;

      //If all are checked
      if (totalItems == checkedItems) {
        masterCheck.prop("indeterminate", false);
        masterCheck.prop("checked", true);
      }
      // Not all but only some are checked
      else if (checkedItems > 0 && checkedItems < totalItems) {
        masterCheck.prop("indeterminate", true);
      }
      //If none is checked
      else {
        masterCheck.prop("indeterminate", false);
        masterCheck.prop("checked", false);
      }
      getSelectedItems();
    });

    function getSelectedItems() {
      var getCheckedValues = [];
      getCheckedValues = [];
      listCheckItems.filter(":checked").each(function() {
        getCheckedValues.push($(this).val());
      });
      $("#selected-values").html(JSON.stringify(getCheckedValues));
    }
  });


Solution for toggling checkboxes using a button, compatible with jQuery 1.9+ where toogle-event is no longer available:

$('.check:button').click(function(){
      var checked = !$(this).data('checked');
      $('input:checkbox').prop('checked', checked);
      $(this).val(checked ? 'uncheck all' : 'check all' )
      $(this).data('checked', checked);
});

DEMO


Below code will work if user select all checkboxs then check all-checkbox will be checked and if user unselect any one checkbox then check all-checkbox will be unchecked.

$("#checkall").change(function () {
    $("input:checkbox").prop('checked', $(this).prop("checked"));
});

$(".cb-element").change(function () {
  if($(".cb-element").length==$(".cb-element:checked").length)
    $("#checkall").prop('checked', true);
  else
    $("#checkall").prop('checked', false);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="all" id="checkall" />Check All</br>

<input type="checkbox" class="cb-element" /> Checkbox  1</br>
<input type="checkbox" class="cb-element" /> Checkbox  2</br>
<input type="checkbox" class="cb-element" /> Checkbox  3


Agreed with Richard Garside's short answer, but instead of using prop() in $(this).prop("checked") you can use native JS checked property of checkbox like,

$("#checkAll").change(function () {
    $("input:checkbox").prop('checked', this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#">
    <p><label><input type="checkbox" id="checkAll"/> Check all</label></p>
    
    <fieldset>
        <legend>Loads of checkboxes</legend>
        <p><label><input type="checkbox" /> Option 1</label></p>
        <p><label><input type="checkbox" /> Option 2</label></p>
        <p><label><input type="checkbox" /> Option 3</label></p>
        <p><label><input type="checkbox" /> Option 4</label></p>
    </fieldset>
</form>


You can try this

    $('.checkAll').on('click',function(){
        $('.checkboxes').prop('checked',$(this).prop("checked"));
    });`

Class .checkAll is a checkbox which controls the bulk action


 $(document).on('change', '.check-all', function () {
   if($(this).prop('checked')) {
      $('.check-box').prop('checked', true)
   }else {
      $('.check-box').prop('checked', false);
   }


Best Solution here Check Fiddle

$("#checkAll").change(function () {
    $("input:checkbox.cb-element").prop('checked', $(this).prop("checked"));
});
$(".cb-element").change(function () {
        _tot = $(".cb-element").length                        
        _tot_checked = $(".cb-element:checked").length;

        if(_tot != _tot_checked){
            $("#checkAll").prop('checked',false);
        }
});
<input type="checkbox" id="checkAll"/> ALL

<br />

<input type="checkbox" class="cb-element" /> Checkbox  1
<input type="checkbox" class="cb-element" /> Checkbox  2
<input type="checkbox" class="cb-element" /> Checkbox  3


If you want to uncheck all the checkboxes on a page, the easiest way is like this:

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


try this

$(".checkAll").click(function() {
    if("checkall" === $(this).val()) {
         $(".cb-element").attr('checked', true);
         $(this).val("uncheckall"); //change button text
    }
    else if("uncheckall" === $(this).val()) {
         $(".cb-element").attr('checked', false);
         $(this).val("checkall"); //change button text
    }
});


Shameless self-promotion: there's a jQuery plugin for that.

HTML:

<form action="#" id="myform">
    <div><input type="checkbox" id="checkall"> <label for="checkall"> Check all</label></div>
    <fieldset id="slaves">
        <div><label><input type="checkbox"> Checkbox</label></div>
        <div><label><input type="checkbox"> Checkbox</label></div>
        <div><label><input type="checkbox"> Checkbox</label></div>
        <div><label><input type="checkbox"> Checkbox</label></div>
        <div><label><input type="checkbox"> Checkbox</label></div>
    </fieldset>
</form>​

JS:

$('#checkall').checkAll('#slaves input:checkbox', {
    reportTo: function () {
        var prefix = this.prop('checked') ? 'un' : '';
        this.next().text(prefix + 'check all');
    }
});​

...and you're done.

http://jsfiddle.net/mattball/NrM2P


try this,

<input type="checkbox" class="checkAll" onclick="$('input[type=checkbox][class=cb-element]').attr('checked',this.checked)">


You can use this.checked to verify the current state of the checkbox,

$('.checkAll').change(function(){
    var state = this.checked; //checked ? - true else false

    state ? $(':checkbox').prop('checked',true) : $(':checkbox').prop('checked',false);

    //change text
    state ? $(this).next('b').text('Uncheck All') : $(this).next('b').text('Check All')
});

$('.checkAll').change(function(){
    var state = this.checked;
    state? $(':checkbox').prop('checked',true):$(':checkbox').prop('checked',false);
    state? $(this).next('b').text('Uncheck All') :$(this).next('b').text('Check All')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
 <input type="checkbox" class="checkAll" /> <b>Check All</b>

   <input type="checkbox" class="cb-element" /> Checkbox  1
   <input type="checkbox" class="cb-element" /> Checkbox  2
   <input type="checkbox" class="cb-element" /> Checkbox  3


Try below code to check/uncheck all checkboxes

jQuery(document).ready(function() {
    $("#check_uncheck").change(function() {
        if ($("#check_uncheck:checked").length) {
            $(".checkboxes input:checkbox").prop("checked", true);
        } else {
            $(".checkboxes input:checkbox").prop("checked", false);
        }
    })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="check_uncheck" id="check_uncheck" /> Check All/Uncheck All
<br/>
<br/>
<div class="checkboxes">
    <input type="checkbox" name="check" id="check" /> Check Box 1
    <br/>
    <input type="checkbox" name="check" id="check" /> Check Box 2
    <br/>
    <input type="checkbox" name="check" id="check" /> Check Box 3
    <br/>
    <input type="checkbox" name="check" id="check" /> Check Box 4
</div>

Try this Demo Link

There is also another short way to do this, checkout below example. In this example check/uncheck all checkbox is checked or not if checked then all wiil be checked and if not all will be uncheck

$("#check_uncheck").change(function() {
    $(".checkboxes input:checkbox").prop("checked",$(this).is(':checked'));
})
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <input type="checkbox" name="check_uncheck" id="check_uncheck" /> Check All/Uncheck All
    <br/>
    <br/>
    <div class="checkboxes">
        <input type="checkbox" name="check" id="check" /> Check Box 1
        <br/>
        <input type="checkbox" name="check" id="check" /> Check Box 2
        <br/>
        <input type="checkbox" name="check" id="check" /> Check Box 3
        <br/>
        <input type="checkbox" name="check" id="check" /> Check Box 4
    </div>


I know this question is old but, I noticed most people are using a checkbox. The accepted answer uses a button, but cannot work with several buttons (ex. one at top of page one at bottom). So here is a modification that does both.

HTML

<a href="#" class="check-box-machine my-button-style">Check All</a>

jQuery

var ischecked = false;
$(".check-box-machine").click(function(e) {
    e.preventDefault();
    if (ischecked == false) {
        $("input:checkbox").attr("checked","checked");
        $(".check-box-machine").html("Uncheck All");
        ischecked = true;
    } else {
        $("input:checkbox").removeAttr("checked");
        $(".check-box-machine").html("Check All");
        ischecked = false;
    }
});

This will allow you to have as many buttons as you would like with changing text and checkbox values. I included an e.preventDefault() call because this will stop the page from jumping to the top due to the href="#" part.


$(function () {
    $('input#check_all').change(function () {
        $("input[name='input_ids[]']").prop('checked', $(this).prop("checked"));
    });
});


Here is a link, which is used to check and uncheck the parent checkbox and all the child checkboxes are getting selected and deselected.

jquery check uncheck all checkboxes Using Jquery With Demo

$(function () {
        $("#select-all").on("click", function () {
            var all = $(this);
            $('input:checkbox').each(function () {
                $(this).prop("checked", all.prop("checked"));
            });
        });
    });


<script type="text/javascript">
    function myFunction(checked,total_boxes){ 
         for ( i=0 ; i < total_boxes ; i++ ){ 
           if (checked){   
             document.forms[0].checkBox[i].checked=true; 
            }else{  
             document.forms[0].checkBox[i].checked=false; 
            } 
        }   
    } 
</script>
    <body>
        <FORM> 
            <input type="checkbox" name="checkBox" >one<br> 
            <input type="checkbox" name="checkBox" >two<br> 
            <input type="checkbox" name="checkBox" >three<br> 
            <input type="checkbox" name="checkBox" >four<br> 
            <input type="checkbox" name="checkBox" >five<br> 
            <input type="checkbox" name="checkBox" >six<br> 
            <input type="checkbox" name="checkBox" >seven<br> 
            <input type="checkbox" name="checkBox" >eight<br> 
            <input type="checkbox" name="checkBox" >nine<br>
            <input type="checkbox" name="checkBox" >ten<br>  s
            <input type=button name="CheckAll" value="Select_All" onClick="myFunction(true,10)"> 
            <input type=button name="UnCheckAll" value="UnCheck All Boxes" onClick="myFunction(false,10)"> 
        </FORM> 
    </body>


add this in your code block, or even click of your button

$('input:checkbox').attr('checked',false);


$(document).ready( function() {
        // Check All
        $('.checkall').click(function () {          
            $(":checkbox").attr("checked", true);
        });
        // Uncheck All
        $('.uncheckall').click(function () {            
            $(":checkbox").attr("checked", false);
        });
    });


removeAttr() no longer works in later versions of jquery. You can use the prop() function.

$(document).ready(function(){
    $('.check:button').click(function(){
        $('input:checkbox').prop('checked',true);
        $(this).val('uncheck all')
    },function(){
        $('input:checkbox').prop('checked', false);
        $(this).val('check all');        
    })
})


Check All with uncheck/check controller if all items is/isnt checked

JS:

e = checkbox id t= checkbox (item) class n= checkbox check all class

function checkAll(e,t,n){jQuery("#"+e).click(function(e){if(this.checked){jQuery("."+t).each(function(){this.checked=true;jQuery("."+n).each(function(){this.checked=true})})}else{jQuery("."+t).each(function(){this.checked=false;jQuery("."+n).each(function(){this.checked=false})})}});jQuery("."+t).click(function(e){var r=jQuery("."+t).length;var i=0;var s=0;jQuery("."+t).each(function(){if(this.checked==true){i++}if(this.checked==false){s++}});if(r==i){jQuery("."+n).each(function(){this.checked=true})}if(i<r){jQuery("."+n).each(function(){this.checked=false})}})}

HTML:

Check ALL controle class : chkall_ctrl

<input type="checkbox"name="chkall" id="chkall_up" class="chkall_ctrl"/>
<br/>
1.<input type="checkbox" value="1" class="chkall" name="chk[]" id="chk1"/><br/>
2.<input type="checkbox" value="2" class="chkall" name="chk[]" id="chk2"/><br/>
3.<input type="checkbox" value="3" class="chkall" name="chk[]" id="chk3"/><br/>
<br/>
<input type="checkbox"name="chkall" id="chkall_down" class="chkall_ctrl"/>

<script>
jQuery(document).ready(function($)
{
  checkAll('chkall_up','chkall','chkall_ctrl');
  checkAll('chkall_down','chkall','chkall_ctrl');
});
 </script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜