简体   繁体   中英

Problems selecting checkboxes with jQuery

I have some problems using following method to select all checkboxes.

I'm using this example:

$(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');        
    })
})

HTML

  <input type="button" class="check" value="check all" />

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

But the button fades out when entering the web page in jQuery 1.11.

What would be a fix for this?

This use of toggle() was removed in jQuery 1.9 ... so you may have to use .click() if you are using jQuery >= 1.9 like

$(document).ready(function () {
    $('.check:button').click(function () {
        $('input[type="checkbox"]').prop('checked', this.value == 'check all');
        $(this).val(function () {
            return this.value == 'check all' ? 'uncheck all' : 'check all';
        })
    })
})

Demo: Fiddle

FYI the toggle event was removed in jQuery 1.9. See api.jquery.com/toggle-event . Instead, try:

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

jsFiddle example

Try this:

 $('.check:button').click(function(){
   if($('input:checkbox:checked').length!=$('input:checkbox').length){
      $('input:checkbox').prop('checked',true);
      $(this).val('uncheck all');
   }else{
      $('input:checkbox').prop('checked',false);
      $(this).val('check all');                  
   }});

Working Demo

Use .prop and modify your jquery code to the below. Though this use click event

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

    });
});

Demo: http://jsfiddle.net/AmitJoki/JJ9XR/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM