Bootstrap Table复选框初始选中状态设置请求示例指导
问题描述
我的表格中,当用户ID为2时,复选框列的渲染代码如下:
<input data-index="0" name="project[users][]" type="checkbox" value="2" checked="checked">
目前默认选中状态正常,但我希望页面加载时仅部分复选框处于选中状态。我查阅了Bootstrap Table官方文档中关于checkbox列的说明:
若指定值,复选框会自动选中。也可通过formatter控制复选框的选中/未选中状态(返回true则选中,返回false则未选中)。
但尝试在<td>上添加data-formatter="() => false;"没有效果,求实现示例。
实现示例
你需要在复选框列的配置中设置formatter,而非直接添加到<td>元素上。以下是两种可行的实现方式:
方式一:自定义formatter函数控制选中状态
通过自定义函数,根据行数据的条件返回true或false,精准控制哪些行的复选框被选中:
<table id="table" data-toggle="table" data-url="你的数据接口地址"> <thead> <tr> <th data-field="id">用户ID</th> <th data-field="name">用户名</th> <th data-field="select" data-checkbox="true" data-formatter="customCheckboxFormatter" > 选择 </th> </tr> </thead> </table> <script> // 自定义格式化函数:仅ID为2、5的行默认选中 function customCheckboxFormatter(value, row) { return row.id === 2 || row.id === 5; } </script>
方式二:通过数据字段自动关联选中状态
如果你的数据源中包含标识是否选中的字段(比如is_default_selected),可以直接将data-checkbox配置为该字段名:
<table id="table" data-toggle="table" data-url="你的数据接口地址"> <thead> <tr> <th data-field="id">用户ID</th> <th data-field="name">用户名</th> <th data-field="select" data-checkbox="is_default_selected" > 选择 </th> </tr> </thead> </table>
此时只要数据源中某行的is_default_selected值为true,该行的复选框就会自动选中。
内容的提问来源于stack exchange,提问作者Héctor
相关产品推荐
相关产品推荐

