JQuery - disable all checkboxes not inside one table

I have a dynamically generated table, each one looks something like this: dynamic id

<table class="innerDatTable" id="dynamically-generated'>
    <caption><h2>Project #</h2></caption>
            <th>SubProject Name</th>
            <th>Date Completed</th>
            <td><input type="checkbox" /></td>


When the user clicks on any of the checkboxes in the table, all other checkboxes that are not inside that table should be disabled (so they can only select subprojects from the same project). Conversely, if the user deactivates all cells within the table, all the checkboxes become available again. I've tried something like this ...

if ($('table input:checked').length > 0) {
    checked = $(this).prop('checked');
    ($('table input[type=checkbox]').attr('id').not($(this).attr('id')))
    .prop('disabled', checked);


The logic here is that if any fields are checked in the table, uncheck all other checkboxes that do not have the same ID as this table (again, IDs are not known in advance). I have mainly followed the answer in this question and tried to change it to my needs, but I cannot get the desired effect (or any effect for this question).

Do I need to put all the other table ids in an array and disable each one in a loop? Can anyone point me in the right direction in terms of syntax, or maybe more logical?


source to share

2 answers

Start by finding all the checkboxes and adding an event handler.
Then find the closest table for the changed checkbox and then all the checkboxes inside that table.

Now that we have that, we can filter the checkboxes in the current table and get everything else so that we can turn them off if the any checkbox is checked in the current table and we can check what's .is(':checked')

in the collection.

var boxes = $('table input[type="checkbox"]')

boxes.on('change', function() {
    var table  = $(this).closest('table'),
        inputs = table.find('input[type="checkbox"]');

    boxes.not( inputs ).prop('disabled', inputs.is(':checked'));




When I have to deal with setting and / or unsettling elements in the DOM, I usually assign a specific class to the active element (for example, "active"). This way, I can iterate through the DOM, discard inactive elements, and not worry about the current "active" element.

In other words, you want to do something like (pseudocode):

$("parent element").find("checkbox elements").not(".active").setInactive()


This method requires the code to set and unset classes for specific elements in the DOM. For example, if you add the active class to the clicked element, but do not remove it, this method will not work (because there will be multiple active elements).

Of course, you will need to make sure you are using the appropriate functionality to disable the inactive checkboxes as well. This Question should lead you in the right direction ...



All Articles