jQuery实现Checkbox全选功能

  • Post author:
  • Post category:其他


jQuery实现勾选CheckAll时选中某一类全部的checkbox;当这一类中的checkbox有一个没有被选中,则CheckAll就不应该被勾选;如果所有的checkbox被选中,则CheckAll应被勾选。

形式如下图:



代码实现:



  1. <


    html


    >





  2. <


    head


    >





  3. <


    meta




    charset


    =


    “utf-8”


    >





  4. <


    title


    >


    </


    title


    >





  5. <


    script




    src


    =


    “jquery.min.js”




    type


    =


    “text/javascript”


    >


    </


    script


    >





  6. <


    script




    type


    =


    “text/javascript”


    >




  7. $(function () {

  8. $(“#checkAll”).bind(“click”, function () {

  9. $(“[

    name


    =


    chkItem


    ]:checkbox”).prop(“checked”, this.checked);


  10. });


  11. $(“input[

    name


    =


    ‘chkItem’


    ]”).click(function() {


  12. var $

    subs


    = $(“input[


    name


    =


    ‘chkItem’


    ]”);


  13. $(“#checkAll”).prop(“checked”,$

    subs.length


    == $subs.filter(“:checked”).length ? true : false);


  14. });

  15. });


  16. </


    script


    >





  17. </


    head


    >





  18. <


    body


    >





  19. <


    div


    >




  20. CheckAll

    <


    input




    id


    =


    “checkAll”




    type


    =


    “checkbox”




    value


    =


    “CheckAll”




    />





  21. </


    div


    >





  22. <


    div


    >





  23. <


    input




    name


    =


    “chkItem”




    type


    =


    “checkbox”




    value


    =


    “Box1”




    />


    Box1



  24. <


    input




    name


    =


    “chkItem”




    type


    =


    “checkbox”




    value


    =


    “Box2”




    />


    Box2



  25. <


    input




    name


    =


    “chkItem”




    type


    =


    “checkbox”




    value


    =


    “Box3”




    />


    Box3



  26. <


    input




    name


    =


    “chkItem”




    type


    =


    “checkbox”




    value


    =


    “Box4”




    />


    Box4



  27. <


    input




    name


    =


    “chkItem”




    type


    =


    “checkbox”




    value


    =


    “Box5”




    />


    Box5



  28. <


    input




    name


    =


    “chkItem”




    type


    =


    “checkbox”




    value


    =


    “Box6”




    />


    Box6



  29. </


    div


    >





  30. </


    body


    >





  31. </


    html


    >