简体   繁体   中英

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> 

 $(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> 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM