You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何基于单元格值禁用DataTables中的行复选框

Fixing Disabled Checkboxes for Rows with "System" Value in DataTables

Looks like your current code has a selector issue that's preventing the checkboxes from being disabled correctly. Let's break down the problem and fix it with reliable solutions.

What's Wrong with Your Current Code?

The main issue is this line:

$("table").closest('tbody tr td').find('input:checkbox').prop('disabled', true);

closest() searches upwards for parent elements, but <table> doesn't have a <tbody><tr><td> as a parent—those are child elements of the table. So this selector doesn't actually find any checkboxes at all. Additionally, looping through the raw json.data in initComplete can lead to mismatches if the table's row order doesn't exactly match the raw JSON order.

DataTables has a createdRow callback that fires right when a row is added to the DOM. This is the most straightforward way to modify rows as they're created:

this.dtOptions = {
  ajax: 'assets/test.json',
  createdRow: function(row, data, dataIndex) {
    // Check if the row's matchType is "System"
    if (data.matchType === "System") {
      // Disable the checkbox in this row
      $(row).find('input:checkbox').prop('disabled', true);
      // Optional: Add a visual cue that the row is disabled
      $(row).css('opacity', 0.7);
    }
  }
};

Solution 2: Fix the initComplete Approach

If you prefer to stick with initComplete, use DataTables' API to safely access rows and their DOM elements instead of raw JSON:

this.dtOptions = {
  ajax: 'assets/test.json',
  initComplete: function(settings, json) {
    const table = new DataTable(settings.nTable);
    // Loop through each row using DataTables API
    table.rows().every(function() {
      const rowData = this.data();
      if (rowData.matchType === "System") {
        // Get the row's DOM node and disable its checkbox
        $(this.node()).find('input:checkbox').prop('disabled', true);
      }
    });
  }
};

Key Takeaways

  • Always use DataTables' built-in callbacks or API to interact with table rows—this avoids selector bugs and order mismatches.
  • createdRow is ideal for row-specific modifications during table initialization, as it works directly with each row as it's rendered.

内容的提问来源于stack exchange,提问作者Rajasekhar

火山引擎 最新活动