Getting values of selected table rows in bootstrap using jquery
Asked Answered
S

4

17

I'm using bootstrap table. In that I want to get Item ID value/values of selected table rows after clicking 'Add to cart' button present on same page.

Table code:

<table data-toggle="table" id="table-style" data-row-style="rowStyle" data-url="tables/data2.json"  data-show-refresh="true" data-show-toggle="true" data-show-columns="true" data-search="true" data-select-item-name="toolbar1" data-pagination="true" data-sort-name="name" data-sort-order="desc" data-single-select="false" data-click-to-select="true" data-maintain-selected="true">
  <thead>
    <tr>
      <th data-field="state" data-checkbox="true"></th>
      <th data-field="id" >Item ID</th>
      <th data-field="name" data-sortable="true">Product Name</th>
      <th data-field="price" data-sortable="true">Actual Price</th>
      <th data-field="discount_price" data-sortable="true">Discount Price</th>
      <th data-field="stock_avail" data-sortable="true">Stock Available</th>
    </tr>
  </thead>
</table>

JQuery code:

$(document).ready(function()
{
   $("#add_cart").click(function()
   {
      //foreach selected row retrieve 'Item ID' values in array;
      //call ajax for otherpage.php?arr='Item ID array';
   });
});

As I'm new in bootstrap I'm trying to tackle this but not getting proper solution anybody please advise me this.

enter image description here

Stone answered 21/8, 2015 at 7:40 Comment(4)
How the tr td data look like?Unfavorable
@NorlihazmeyGhazali- please see my edited question.Stone
Opss sorry, once again, can you sure the HTML structure of table rows, wanna see how the HTML rendered. Just a few line enoughUnfavorable
@NorlihazmeyGhazali- I uses bootstrap table plugins for table.Stone
H
25

Just use the check.bs.table and uncheck.bs.table events to collect your checked rows.

BS-Table Basic Events

Here is an example:

var checkedRows = [];

$('#eventsTable').on('check.bs.table', function (e, row) {
  checkedRows.push({id: row.id, name: row.name, forks: row.forks});
  console.log(checkedRows);
});

$('#eventsTable').on('uncheck.bs.table', function (e, row) {
  $.each(checkedRows, function(index, value) {
    if (value.id === row.id) {
      checkedRows.splice(index,1);
    }
  });
  console.log(checkedRows);
});

$("#add_cart").click(function() {
  $("#output").empty();
  $.each(checkedRows, function(index, value) {
    $('#output').append($('<li></li>').text(value.id + " | " + value.name + " | " + value.forks));
  });
});
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.8.1/bootstrap-table.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-table/1.8.1/bootstrap-table.min.js"></script>

<table id="eventsTable"
       data-toggle="table"
       data-height="300"
       data-url="https://api.github.com/users/wenzhixin/repos?type=owner&sort=full_name&direction=asc&per_page=100&page=1"
       data-pagination="true"
       data-search="true"
       data-show-refresh="true"
       data-show-toggle="true"
       data-show-columns="true"
       data-toolbar="#toolbar">
    <thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="name">Name</th>
        <th data-field="stargazers_count">Stars</th>
        <th data-field="forks_count">Forks</th>
        <th data-field="description">Description</th>
    </tr>
    </thead>
</table>

<button id="add_cart">Add to card</button>
<ul id="output"></ul>
Harless answered 21/8, 2015 at 8:38 Comment(8)
That's great, perfect.Stone
Hi, It is posible to set this code (show only selected items) to work with a normal table (data source to be from html, not from JSON)? Sorry, I don't know JS. Thank you for any help.Hoskinson
@Hoskinson It shouldn't make any difference if the data is static HTML or coming from JSON. Did you try it out ?Harless
Yes. My problem is that I can't manage to do that from JS for this sniped: link . Can you please help?Hoskinson
how do you get values of all items if you check box all?Hornstein
Link (bootstrap-table.com/examples/#events) in the answer is not working anymore.Mikiso
More elegant in 2020: .on('uncheck.bs.table', function (e, row) { checkedRows = checkedRows.filter(item => item.id != row.id) });Psychotechnics
Not working when check the page global check for all visible elements. Best use $('#id').bootstrapTable('getSelections');Normie
B
9

To get the selected (checked) rows, use getSelections method.

Note that if you are using pagination, then you have to use the maintainMetaData table option.

Here is an example which displays selected product's names when user clicks on Show Selected Rows button:

var $table = $('#myTable');

function getRowSelections() {
  return $.map($table.bootstrapTable('getSelections'), function(row) {
    return row;
  })
}

$('#showSelectedRows').click(function() {
  var selectedRows = getRowSelections();
  var selectedItems = '\n';
  $.each(selectedRows, function(index, value) {
    selectedItems += value.name + '\n';
  });

  alert('The following products are selected: ' + selectedItems);
});
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/bootstrap-table.min.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/[email protected]/dist/bootstrap-table.min.js"></script>

<div id="toolbar">
  <button id="showSelectedRows" class="btn btn-primary" type="button">Show Selected Rows</button>
</div>

<table id="myTable" data-toolbar="#toolbar" data-toggle="table" data-maintain-meta-data="true">
  <thead>
    <tr>
      <th data-field="state" data-checkbox="true"></th>
      <th data-field="id">Item ID</th>
      <th data-field="name" data-sortable="true">Product Name</th>
      <th data-field="price" data-sortable="true">Price</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>1</td>
      <td>Chair</td>
      <td>$80</td>
    </tr>
    <tr>
      <td></td>
      <td>2</td>
      <td>Sofa</td>
      <td>$500</td>
    </tr>
    <tr>
      <td></td>
      <td>3</td>
      <td>Desk</td>
      <td>$300</td>
    </tr>
    <tr>
      <td></td>
      <td>4</td>
      <td>Rug</td>
      <td>$200</td>
    </tr>
  </tbody>
</table>
Blueprint answered 10/2, 2020 at 23:26 Comment(4)
This to me is a much cleaner solution and works perfectlyGallous
Awesome solution, it's clean and uses the own bootstrap table methods, works great!Perice
@hooman is this works for server side pagination?Hawthorn
@Rahul: of course not, JavaScript works on the frontendBlueprint
U
2

Here is example give it to you :

HTML

<table id="table-style">
<thead>
    <tr>
        <th data-field="state" data-checkbox="true"></th>
        <th data-field="id">Item ID</th>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>5</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>15</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" />
        </td>
        <td>10</td>
    </tr>
</thead>
</table>

<button>Add to cart</button>

JS

var arr;
$('button').click(function(){
  arr = $('#table-style').find('[type="checkbox"]:checked').map(function(){
      return $(this).closest('tr').find('td:nth-child(2)').text();
  }).get();

  console.log(arr);
});

DEMO

Unfavorable answered 21/8, 2015 at 8:12 Comment(6)
sorry your solution doesn't matching for me, the table takes data from data-url="tables/data2.json" and check-boxes are automatically taken by bootstrap. Then how can I get Item ID value if checked particular?Stone
Do you try already? Doesn't matter where the data came from and what important is at end of how DOM rendered your data into page. Inspect element on table then copy it structure then paste it in here for more specified solutionUnfavorable
yse I'm uses this onlyStone
@Vg. See DavidDomain answer. Those plugin have their own event function for that.Unfavorable
Thanks for taking efforts, DavidDomain's answer is correct.Stone
Yes, glad to hear that!Unfavorable
S
0

Bootstrap table has a function getSelections

with the javascript funciton you can get all selected rows. (your checkobx fiels should be bound to data-field="state")

            function getIdSelections() {
            return $.map($table.bootstrapTable('getSelections'), function (row) {
                return row.Id
            });
        }
Supervision answered 10/7, 2018 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.