Jquery select all if not disabled

后端 未结 4 660
遥遥无期
遥遥无期 2020-12-18 21:46

I am using the following script to select all checkboxes with a given class.

$(document).ready(function(){ // 1
    // 2
    $(\':checkbox.selectall\').on(\'         


        
相关标签:
4条回答
  • 2020-12-18 22:01

    Hm... interresting attempt, but you can't use a jQuery object inside a selector, as the selector is just a plain string.

    The selector for excluding the disabled elements would be :not(:disabled), so your code should be:

    $(document).ready(function(){
      $(':checkbox.selectall').on('click', function(){
        $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked"));
        $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').trigger("change");
      });
    });
    

    Note that you can chain calls, so you don't have to select the items twice:

    $(document).ready(function(){
      $(':checkbox.selectall').on('click', function(){
        $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked")).trigger("change");
      });
    });
    
    0 讨论(0)
  • 2020-12-18 22:02

    This does not do the same as your original code. It would only trigger change for those that was not changed. I've assummed you wished to trigger change for all the once you changed

    $(':checkbox.selectall').on('click', function(){
            $(':checkbox .'+ $(this).data('checkbox-name')).not(':disabled').prop("checked", $(this).prop("checked")).trigger("change");
        });
    
    0 讨论(0)
  • 2020-12-18 22:04

    Use a combonation of the .not() function and :disabled selector to exclude these.

    $(':checkbox[class='+ $(this).data('checkbox-name') + ']').not(':disabled').prop("checked", $(this).prop("checked"));
    $(':checkbox[class='+ $(this).data('checkbox-name') + ']').not(':disabled').trigger("change");
    

    .not() also exists as a selector as :not() and could be used as follows:

     $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').prop("checked", $(this).prop("checked"));
     $(':checkbox[class='+ $(this).data('checkbox-name') + ']:not(:disabled)').trigger("change");
    
    0 讨论(0)
  • 2020-12-18 22:10

    Here is what I usually do:

    $(function(){
        $(".selectall").live('change', function(){
            if($(this).is(":checked"))
            {
                $("input:checkbox:not(:disabled)." + $(this).data('checkbox-name')).prop("checked", "true");
            }
            else
            {
                $("input:checkbox:not(:disabled)." + $(this).data('checkbox-name')).prop("checked", "false");
            }
        });
    });
    

    I hope it helps :)

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