如何在列表及DataTable中默认选中指定复选框与最后一项复选框
Let's break down how to solve both your requirements using your existing code as a base. First, a quick note: your snippet uses <input type="radio"> but you mentioned checkboxes—so I'll adjust the input type to checkbox below (if you actually need radio buttons, just swap it back and adjust the logic accordingly).
1. Default Check a Specific List Item
To pre-select a checkbox with a known identifier (like a specific row.id), add the checked attribute conditionally when rendering the input:
// Replace YOUR_TARGET_ID with the ID of the item you want to pre-select const targetId = "YOUR_TARGET_ID"; // Modified rendering code const html = '<div class="form-check">' + '<label class="form-check-label">' + '<input type="checkbox" name="check-box-product" class="form-check-input" value="' + row.id + '" ' + (row.id === targetId ? 'checked' : '') + '> ' + '<span class="product-name">' + row.data + '</span> <a href="' + row.url + '" target="_blank"><i class="fa fa-external-link"></i></a> ' + // Rest of your HTML content... '</label></div>';
This checks if the current row's ID matches your target, and adds the checked attribute only for that item.
2. Always Default Check the Last Item in DataTable
If you need the last checkbox in the current DataTable view (including after pagination/sorting) to be checked automatically, use DataTable's drawCallback function—it runs every time the table redraws:
Option 1: When Rendering Rows Manually
If you're building the HTML in a loop over your data array:
// Assume your full dataset is stored in dataArray dataArray.forEach((row, index) => { const isLastItem = index === dataArray.length - 1; const html = '<div class="form-check">' + '<label class="form-check-label">' + '<input type="checkbox" name="check-box-product" class="form-check-input" value="' + row.id + '" ' + (isLastItem ? 'checked' : '') + '> ' + '<span class="product-name">' + row.data + '</span> <a href="' + row.url + '" target="_blank"><i class="fa fa-external-link"></i></a> ' + // Rest of your HTML content... '</label></div>'; // Append the HTML to your table container });
Option 2: DataTable Native Callback (Better for Dynamic Tables)
For tables with pagination, sorting, or search features, use drawCallback to ensure the last checkbox is checked after every table redraw:
$('#yourDataTableId').DataTable({ // Your existing DataTable configuration (columns, ajax, etc.) drawCallback: function() { // Get the last checkbox in the table body const lastCheckbox = $(this.api().table().body()).find('input[type="checkbox"]').last(); // Set it to checked lastCheckbox.prop('checked', true); } });
Also, fix the syntax error in your original code: you had extra double quotes around the value attribute—make sure it's formatted like value="' + row.id + '" instead of "value="' + row.id + '" ".
内容的提问来源于stack exchange,提问作者CerraossoUC

