You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:20:09