Question

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.

Was it helpful?

Solution

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 */
})
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top