How do I select all check box when I click on Select button using jQuery

前端 未结 9 936
遇见更好的自我
遇见更好的自我 2020-12-21 20:22

I have HTML page which have multiple check boxes and individually they can be checked. I have button select, so what I am suppose to do is. When I click on sel

相关标签:
9条回答
  • 2020-12-21 20:28

    This will definitely works.

    $("#selectAll").click(function(){
        var checked = !$(this).data('checked');
        $('.btn-chk').prop('checked', checked);         
        $(this).data('checked', checked);
    });
    
    0 讨论(0)
  • 2020-12-21 20:30

    If you want to toggle the checkbox state, you can do like this

    var chkd = true;
    $('#selectAll').click(function(event) {
        $(":checkbox").prop("checked", chkd);
        chkd = !chkd;
    });
    

    Fiddle

    0 讨论(0)
  • 2020-12-21 20:31

    inside the "click" function "this" is button and not a checkbox. and button property checked is underfined. "$('.btn-chk').each" - is loop on each element with class ".btn-chk", in your HTML is buttons and not an checkboxes.

    in your context the "#selectAll" must be a checkbox and put class '.btn-chk' on your checkboxes

    0 讨论(0)
  • 2020-12-21 20:34

    An simple way is like below:

    $(function() {
        $('#selectAll').click(function() {
            $(':checkbox').prop('checked', !$(':checkbox').prop('checked'));
        });
    });
    

    The Demo.

    0 讨论(0)
  • 2020-12-21 20:36

    #selectAll is a button, it doesn't have a checked property, but one could emulate that with a data attribute instead.

    Secondly, .btn-chk isn't a checkbox either, so it can't be checked, you have to target the checkboxes

    $(document).ready(function() {
        $('#selectAll').click(function(event) {
            var checked = !$(this).data('checked');
    
            $('.btn-chk').next().prop('checked', checked);
    
            $(this).data('checked', checked);
        });
    
    });
    

    FIDDLE

    0 讨论(0)
  • 2020-12-21 20:38

    Change your jQuery code to

     $('#selectAll').click(function(event) {  //on click 
        if($('.hidden').prop('checked') == false) { // check select status
            $('.hidden').each(function() { //loop through each checkbox
                this.checked = true;  //select all checkboxes with class "checkbox1"               
            });
        }else{
            $('.hidden').each(function() { //loop through each checkbox
                this.checked = false; //deselect all checkboxes with class "checkbox1"                       
            });         
    
        }
    });
    

    This will toggle between checked and unchecked of the checkboxes when you click the button.

    0 讨论(0)
提交回复
热议问题