bootstrap table getSelections获取选中行数据的方法

getSelections是一个bootstrap table一个重要而经常用到的方法,该方法获取获取你选中行的数据,需要注意和getAllSelections方法的区别,getAllSelections会返回包含搜索刷选后的选中的数据。
方法返回的对象格式如下:

[{"Id":1,"ProductName":"香蕉","StockNum":"100","checked":true},
{"Id":3,"ProductName":"车厘子","StockNum":"2010","checked":true}]

前端分页getSelections

如果使用的是前端分页模式,为了把属性maintainSelected设置为ture,getSelections也可以同时获取多页选中的数据。

//获取选中行的数据
 var rows = $('#table').bootstrapTable('getSelections');
//rows选中行的数据对象数组
alert(JSON.stringify(rows));
// rows对象的格式
// [{"Id":1,"ProductName":"香蕉","StockNum":"100","checked":true},{"Id":3,"ProductName":"车厘子","StockNum":"2010","checked":true}]

服务器端分页getSelections

服务器端分页如果需要同时获取多给分页选中的行数据,需要先设置保持状态属性。

//首先,设置maintainSelected :true开启保持分页状态
$('#table').bootstrapTable({
            url: '/package/bootstrap-table-1.14.1/data.json',
            pagination: true,
            search: true, 
            columns: columns,
            pageSize:2,
            maintainSelected :true,
            toolbar:"#toolbar"
 });
//获取选中的数据
var rows = $('#table').bootstrapTable('getSelections');

在线试一试

完整代码

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <script src="https://www.itxst.com/package/bootstrap-table-1.14.1/jquery-3.3.1/jquery.js"></script>
    <link href="https://www.itxst.com/package/bootstrap-4.3.1/css/bootstrap.css" rel="stylesheet" />
    <link href="https://www.itxst.com/package/bootstrap-table-1.15.3/bootstrap-table.css" rel="stylesheet" />
    <script src="https://www.itxst.com/package/bootstrap-table-1.15.3/bootstrap-table.js"></script>
    <title>Bootstrap Table getSelections例子</title>
    <style>
        .table-demo {
            width: 80%;
            margin: 30px auto 0px auto;
        }
    </style>
</head>
<body>
  <div id="toolbar">
    <button onclick="getSels()">获取选中项目 </button>
  </div>
    <div class="table-demo">
        <table id="table"></table>
    </div>
    <script>
       // 设置需要显示的列
        var columns = [{
            field :"checked", 
            title: '编号', 
            checkbox:true
        }, {
            field: 'ProductName',
            title: '名称'
        }, {
            field: 'StockNum',
            title: '库存'
        }];

        $('#table').bootstrapTable({
            url: '/package/bootstrap-table-1.14.1/data.json',
            pagination: true,//开启分页
            search: true, //开启刷选
            columns: columns,
            pageSize:2,
            maintainSelected :true,
            toolbar:"#toolbar"
        });
      
       function getSels()
      {
      var rows = $('#table').bootstrapTable('getSelections');
       alert(JSON.stringify(rows));
      }
 
    </script>
</body>
</html>