Getting the checked rows in datatables

Getting the checked rows in datatables

ndegwerndegwer Posts: 7Questions: 2Answers: 0
edited May 2017 in Free community support

Hello,

I have a datatable with a checkbox column which i use to delete.

How can i get the checked rows. I have reached this point.

`
$('#delete-client').on('click', function () {

    client_table.$('input[type="checkbox"]').each(function () {
<?php ?? }); }); ` ?>

Answers

  • erelcolakerelcolak Posts: 3Questions: 1Answers: 0

    You must get "selected" rows in table; it's much more easy to get row values. Let me show you in example

    var dataTableRows = table.rows({selected: true}).data().toArray();
    var arrTableSelectedRowsRendered = [];
    for (var i = 0; i < dataTableRows.length; i++){
    dataTableRows[i] = dataTableRows[i].slice(1, dataTableRows[i].length);
    arrTableSelectedRowsRendered.push( dataTableRows[i].slice( 0, dataTableRows[i].length-1) ) );
    }

  • ndegwerndegwer Posts: 7Questions: 2Answers: 0

    Thanks for the reply,

    Your code gets all the rows but not the selected, and not the row id

  • Rob BrunRob Brun Posts: 56Questions: 2Answers: 14
    edited May 2017

    Hi ndegwer, if you have the rowId option set on your datatable and assuming you are using the select extension you can get the collection of selected rows like this.

    var selectedRows = client_table.rows({ selected: true }).ids(true);
    

    Then to remove a row it would look like this

    client_Table.row(selectedRows[0]).remove();
    

    This would remove the row at the zero index of your selected row collection.

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    Worth noting that if you are using your own checkboxes (which wasn't clear in your other thread on this topic) then the selected row modifier isn't going to help you.

    You'd need to do:

    var rows = $( client_table.$('input[type="checkbox"]').map(function () {
      return $(this).closest('tr');
    } ) );
    

    Allan

  • ndegwerndegwer Posts: 7Questions: 2Answers: 0

    Hello, Thanks for the reply.

    Here is my code: Please add the code TAG on the text box

    $(document).ready(function () {

    client_table = $('#dataTables-clients').DataTable({
        responsive: true,
        'columnDefs': [{
                'targets': 0,
                'searchable': false,
                'orderable': false,
                'render': function (data, type, full, meta) {
                    return '<input type="checkbox" />';
                }
            }],
    });
    
    $('#delete-client').on('click', function () {
    
        //?? THE CODE AM LOOKING FOR
    });
    

    });

    the code am looking for is the ROW ID

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    Very happy to write the code for you. That would fall under the priority support options. Alternatively, use the code I've given above which is about 80% of the way there. You just need to modify it to get the id from each row.

    Allan

  • ndegwerndegwer Posts: 7Questions: 2Answers: 0

    Ok thanks for you support, i think datatables is not for me at this point

  • bindridbindrid Posts: 730Questions: 0Answers: 119

    If you are interested, I built this a month ago for another Datatable user.

    It keeps a running total of all of the rows that have been checked by the user.

    http://jsbin.com/joxiri/4/edit?html,js,output

  • ndegwerndegwer Posts: 7Questions: 2Answers: 0
    edited May 2017

    Tank you bindrid for the support

    edited Removed advertising links. This isn't the place for that :smile:

  • deep007deep007 Posts: 17Questions: 2Answers: 0
    edited January 2018

    hey @allan..
    M stuck at same point I used your code..
    It's working fine but just for one checkbox..
    What should I do to get multiple but not all the checked value from the table..

    Thanks in advance...

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    There are many ways to handle checkboxes with Datatables. It would help if you showed the relevant JS code of what you are doing so we can help.

    Kevin

  • deep007deep007 Posts: 17Questions: 2Answers: 0

    `

    <

    script type="text/javascript" charset="utf-8">
    $(document).ready(function () {
    $('#calltable').dataTable({
    "bPaginate": true,
    "bLengthChange": true,
    "bFilter": true,
    "bSort": true,
    "bInfo": true,
    "bAutoWidth": true,
    "bStateSave": true,
    "aoColumnDefs": [
    { 'bSortable': false, 'aTargets': [ -1,0] }
    ]
    });

        // trashcan is the id of the icon users click to delete items 
        // onclick get all the checked rows and do something 
        $("#trashcan")
        .click(function () {
    
       //Need code her to run this..
       //var rows = $( client_table.$('input[type="checkbox"]').map(function () {
        //return $(this).closest('tr');
        //This above code is working fine but just for one checked checkbox...
       // I want to apply it for multiple checkbox..
    

    } ) );
    });

        });
    
        });`
    
  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    This code:

    var rows = $( client_table.$('input[type="checkbox"]').map(function () {
      return $(this).closest('tr');
    } ) );
    

    Try changing it to something like this to return only checked checkboxes:

    var rows = $( client_table.$('input[type="checkbox"]').map(function () {
      return $(this).prop("checked") ? $(this).closest('tr') : null;
    } ) );
    

    Kevin

  • deep007deep007 Posts: 17Questions: 2Answers: 0

    Thanks kevin that work fine for me :smiley:

  • joellerjoeller Posts: 48Questions: 9Answers: 0

    @Kevin and @allan

    I viewed with interest several pages about using checkboxes. I seen a number that use built in DataTables check boxes. The issue with those is that they return a row id as opposed to the Database primary key that uniquely identifies the record in the database about which I am concerned.

    I saw this entry that was about using html inputs of the type checkbox (which is what I am doing.)

    I saw this code above that was written

          var rows = $( client_table.$('input[type="checkbox"]'String).map(function () {
          
         return $(this).closest('tr'String);
       
          } ) );
    

    This appears to resolve my question about getting the things that are checked.

    However my initial problem is that I cannot get my checkboxes to display at all.
    I've got this table


    <table id="tableRiks" class="tableNonlinkedRequirements" title="Table of Linked RIKs" style="width:100%;"> <thead> <tr> <th style="font-size:10pt;white-space:nowrap;width:12%"><br />Link</th> <th style="font-size:10pt;white-space:nowrap;width:12%"><br />RIK Name</th> <th style="font-size:10pt;white-space:nowrap;width:12%"><br />Requirement Number</th> <th style="font-size:10pt;white-space:nowrap;width:12%"><br />Requisition Number</th> <th style="font-size:10pt;white-space:nowrap;width:12%"><br />Stock Issue Qty</th> <th style="font-size:10pt;white-space:nowrap;width:12%"><br />Stock Ship Date</th> <th style="font-size:10pt;white-space:nowrap;width:12%">Customer Code<br />Providing Stock</th> <th style="font-size:10pt;white-space:nowrap;width:12%">Customer<br />Providing Stock</th> </tr> </thead> <tbody id="tableRIKsBody"> @foreach (var item in Model.RIKs) { <tr> <td> <input type="checkbox" value="@(item.RIKID)" /> </td> <td class="ReqNum">@(item.RIKName)</td> <td class="ReqNum">@(item.ReqNum)</td> <td class="ReqNum">@(item.RequistionNumber)</td> <td>@(item.StockIssueQty)</td> <td id="StockShipDate" class="ShipDate">@(item.StockShipDate)</td> <td>@(item.CCDesc)</td> <td>@(item.Customer)</td> </tr> } </tbody> </table>

    I set this up as a datatable using thiscode

                editor = $('#tableRiks').DataTable(
                {
    
                    dom: "Bfrtip",
                    //ajax: thisURL,
                    columns: [
                        {
                            data: null,
                            defaultContent: '',
                            className: 'select-checkbox',
                            orderable: false
                        },
                        { data: "RIKName" },
                        { data: "ReqNum" },
                        { data: "RequistionNumber" },
                        { data: "StockIssueQty" },
                        { data: "StockShipDate" },
                        { data: "CCDesc" },
                        { data: "Customer" }
                    ],
                    order: [1, 'asc'],
                    select: {
                        style: 'os',
                        selector: 'td:first-child'
                    },
                    buttons: [
                        {
                            text: "Add",
                            action: function (e, dt, node, config) {
                                AddNewRIKDialog(e);
                            }
                        },
                        {
                            text: "Edit",
                            action: function () { alert("Edit RIK"); }
                        },
                        {
                            text: "Remove",
                            action: function () { alert("remove RIK"); }
                        }
                    ]
                });
    
            });
    

    But I don't get either the built in checkboxes or the inputs of type checkbox showing.
    I did not realize until this minute that the code I was using actually has coding for the built in checkboxes in it. But if so then why don't they show?

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    But I don't get either the built in checkboxes or the inputs of type checkbox showing.

    I'm not sure why the input type checkboxes aren't showing. It seems like your for loop should build them correctly.

    The "built in" checkboxes come from the Select extension. The className: 'select-checkbox' causes the select extension to display the checkboxes. If these aren't showing then it would suggest you aren't loading the JS and CSS for the Select extension.

    If you are only using this checkbox to select row(s) then I would suggest the following:
    1. Create a hidden column to store the ID
    2. Remove your input checkbox from your for loop and load the Select extension checkbox

    Here is an example based on your config:
    http://live.datatables.net/tiwovada/1/edit

    It uses the select event to display the ID of the selected row. There is also a function that will provide an array of selected row ID's using pluck() and toArray(). If you enable multi select then you can get all the selected row ID's in the array.

    Kevin

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    The checkboxes aren't being shown because of this initialisation for the first column:

                    data: null,
                    defaultContent: '',
    

    Basically that is telling DataTables to throw away anything it does find in the HTML for the first column and use an empty string instead.

    Allan

  • joellerjoeller Posts: 48Questions: 9Answers: 0

    Thanks Kevin and Allan;
    I took you example code Kevin and everything is being shown. I want to limit the users to making a single selection at a time so I chose to make the selkect tyle = "single". I am trying to figure out whether the var Id in the btnShow event handler will be an int or an array of int when I use "rows"({selected : true})

    Also I am thinking that the btnShow event handler and the variable "table" are not visible to any function outside the document.ready function. (Found this out last week thanks to Allan). So should all of these be declared outside the document.Ready event handler?

    In that vein, I am not sure about what is being signified by the parameter e of the button event handlers in my code (which I copied from the website and which I added when I read something that said the button action would not work without those parameters)

    buttons: [
                        {
                            text: "Add",
                            action: function (e, dt, node, config) {
                                AddNewRIKDialog(e);
                            }
    
  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    = "single". I am trying to figure out whether the var Id in the btnShow event handler will be an int or an array of int when I use "rows"({selected : true})

    Yes it will be an array if you use rows(). If you are selecting only 1 row then you can use row() and just get the data without the array, for example:

      $("#btnShow").click(function(){
        var data = table
                  .row({ selected: true })
                  .data();
        console.log(data.RIKID);   //display int value
      });
    

    the variable "table" are not visible to any function outside the document.ready function. So should all of these be declared outside the document.Ready event handler?

    You could do that. Or you can always get an API instance using something like this: var api = $('#tableRiks').DataTable();.

    not sure about what is being signified by the parameter e of the button event

    This doc describes the parameters for the action function:
    https://datatables.net/reference/option/buttons.buttons.action

    Whether you need to use any of the parameters depends on what you want the function to do. You can change AddNewRIKDialog(e); to console.log(e); to see what the e parameter contains.

    Kevin

  • joellerjoeller Posts: 48Questions: 9Answers: 0
    edited February 2018

    Turns out the "single" value, of the select's style attribute, does not restrict the user to clicking only one row. How would I go about enforcing this on this table?
    Thanks in advance.

  • kthorngrenkthorngren Posts: 21,301Questions: 26Answers: 4,946

    You can set the Select Extension to use singe by setting the select style option to single:
    https://datatables.net/reference/option/select.style

    Kevin

This discussion has been closed.