Rataiczak24
Rataiczak24

Reputation: 1042

Enable checkbox if other checkbox is checked

I have a table with multiple columns, 2 of them being checkboxes. However, I only want the first column of checkboxes to be enabled on page load. I only want the second column of checkboxes to be enabled if a checkbox is checked in the first column.

My current code will do that but I am wanting the checked checkbox to only enable/disable the specific checkbox in that same row, not all of them in the entire column.

How can I do this? This is what I have so far:

$(document).ready(function() {
  $('.paid').attr('disabled', true);

  $('.selected').change(function() {
    $('.paid').attr('disabled', !this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--checkbox that is enabled on page load-->
<td align="center"><input type="checkbox" id="check" class="selected" name="selected"></td>

<!--checkbox that will be enabled/disabled based on checkbox above-->
<td align="center"><input type="checkbox" id="paid" class="paid" name="selected"></td>

Upvotes: 0

Views: 1863

Answers (2)

Taplar
Taplar

Reputation: 24965

$(document).ready(function() {
  $('.paid').attr('disabled', true);

  $('.selected').change(function() {
    //find only the paid in the same row as the selected checkbox
    $(this).closest('tr').find('.paid').attr('disabled', !this.checked);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <table id="myTable">
            <tr>
                <td align="center"><input type="checkbox" id="check" class="selected" name="selected"></td>
                <td align="center"><input type="checkbox" id="paid" class="paid" name="selected"></td>
            </tr>
            <tr>
                <td align="center"><input type="checkbox" id="check" class="selected" name="selected"></td>
                <!-- checkbox that will be enabled/disabled based on checkbox above --> 
                <td align="center"><input type="checkbox" id="paid" class="paid" name="selected"></td>
            </tr>

        </table>

Upvotes: 3

Mia Lemoine
Mia Lemoine

Reputation: 157

This should do the trick:

$(document).ready(function () {
  $('.paid').attr('disabled', true);

  $('.selected').change(function(){
    $(this).parent().siblings().find('.paid').attr('disabled', !this.checked);
  });
});

That will make sure it find the .paid checkbox next to your .selected checkbox.

Upvotes: 3

Related Questions