check/uncheck all checkboxes with jquery 1.10.2

拈花ヽ惹草 提交于 2019-12-25 01:53:41

问题


There are quite a few questions asked on this topic, but none worked for my problem as I don't know how to apply them in my code - I'm new to jQuery.

Here is my HTML page:

<div id="one">
   <div id="positionable2">
      <div id="xyz2">
         <table id="tab1">
           <tr><td class="header"><input type=checkbox id=cbselectall /></td></tr>
           <tr><td ><input type=checkbox name=case /></td></tr>
           <tr><td ><input type=checkbox name=case /></td></tr>
           <tr><td ><input type=checkbox name=case /></td></tr>
         </table>
      </div>
   </div>
</div>

Now my jQuery looks something like below:

$(function () {
    $("#one #positionable2 #xyz2 #tab1 #cbselectall").click(function () {
        if ($("#one #positionable2 #xyz2 #tab1 #cbselectall").is(':checked')) {
            $("#one #positionable2 #xyz2 #tab1 input[type=checkbox]").each(function () {
                //$(this).attr("checked", true);
                $(this).prop("checked", true);
            });

        } else {
            $("#one #positionable2 #xyz2 #tab1 input[type=checkbox]").each(function () {
                //$(this).attr("checked", false);
                $(this).prop("checked", false);
            });
        }
    });
});

Please note that I have other columns in the table, the column with checkbox is the first column. Upon clicking the checkbox in the table header, other columns on data row should get selected and vice versa. Somehow this is not working.

As I'm new to jQuery, somehow I'm unable to make it work. Please help.


回答1:


first off you don't need to specify the heirarchy in each of your selectors.

$("#cbselectall").on('click', function() {

    $(this)
    .parents('table') // go to the table element
    .find(':checkbox') /* find all checkboxes (note you might need to specifiy 
                          if you have other checkboxes in the table that shouldn't get checked 
                       */
    .prop('checked', $(this).is(':checked')); /* set the checked value to be the value
                                                 of the check all checkbox */
})


来源:https://stackoverflow.com/questions/22161254/check-uncheck-all-checkboxes-with-jquery-1-10-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!