0

I try to select multiple rows by checkboxes in datatables jquery plugin in order to pass data to another form.

I was doing something but my code just returns selected row in the current datatable active page.

This is my form which is filled with data coming from jquery:

   <div class="widget-footer">

      <button id="BtnClick" class="btn btn-sm btn-success" type="submit">
          صدور
      </button>
      @using (@Html.BeginForm("LineRegimeSave", "DietTherapy", FormMethod.Post, new { id = "hiddenForm" }))
      {
          <input type="hidden" name="BreakFast" value="" />
          <input type="hidden" name="Snake1" value="" />
          <input type="hidden" name="Lunch" value="" />
          <input type="hidden" name="Snake2" value="" />
          <input type="hidden" name="Snake3" value="" />
          <input type="hidden" name="Dinner" value="" />
          <input type="hidden" name="Snake4" value="" />
          <input type="hidden" name="AdviseText" value="@TempData["Advise"].ToString()" />
          <input type="hidden" name="docFooterId" value="@TempData["footerId"].ToString()" />
      }
  </div>

And this is my query :

        var datasets = {};
        $("#BtnClick").click(function () {

           $.each(
                $("input[type=checkbox]"),
                function() {
                    var catName = $(this).attr('name');
                    datasets[catName] = {
                        label: catName,
                        data: []
                    };
                });

           $.each(
                $("input[type=checkbox]:checked"),
                function () {
                    var catName = $(this).attr('name');
                    datasets[catName].data.push($(this).val());
                });
            var data ={};
            $.each(
                datasets,
                function (item, dt) {
                    var name = item;
                    var value = dt['data'].join(",");
                    data[name] = value;
                }
            );

            $("#hiddenForm").autofill(data);
            $("#hiddenForm").submit();

And you can see my table :

<div class="panel panel-default">
    <div class="panel-heading">
        <h4 class="panel-title">
            <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="false" class="collapsed">
                <i class="fa fa-lg fa-angle-down pull-right"></i>
                <i class="fa fa-lg fa-angle-up pull-right"></i>
                وعده صبحانه
            </a>
        </h4>
    </div>
    <div id="collapseOne" class="panel-collapse collapse" aria-expanded="false" style="height: 0;">
        <div class="panel-body no-padding">
                <table id="dt_basic" class="table table-striped table-bordered table-hover dataTable no-footer" role="grid" aria-describedby="datatable_col_reorder_info" style="width: 100%;" width="100%">
                    <thead>
                        <tr role="row">
                            <th data-hide="phone" class="sorting_asc" tabindex="0" aria-controls="datatable_col_reorder" rowspan="1" colspan="1" style="width: 31px;" aria-sort="ascending" aria-label="ID: activate to sort column descending">ردیف</th>
                            <th data-class="expand" class="expand sorting" tabindex="0" aria-controls="datatable_col_reorder" rowspan="1" colspan="1" style="width: 300px;" aria-label="Name: activate to sort column ascending">رژیم</th>
                            <th class="sorting" aria-controls="datatable_col_reorder" rowspan="1" colspan="1" style="width: 50px;" aria-label="Phone: activate to sort column ascending">کالری</th>
                            <th aria-controls="datatable_col_reorder" rowspan="1" colspan="1" style="width: 20px;" aria-label="Phone: activate to sort column ascending">انتخاب</th>
                        </tr>
                    </thead>
                    <tbody>
                        @{
                            //string[] cal = new[] {breakfast, snake1, lunch, snake2, snake3, dinner, snake4};

                            if (Model.Any())
                            {
                                int index = 1;
                                var breakFast = Model.Where(a => a.Mealses.Any(b => b.MealsName == "BreakFast") && a.Calories.ToString() == @ViewBag.cal[0].ToString()).ToList();
                                foreach (var itDiet in breakFast)
                                {
                                    var rowCls = "odd";
                                    rowCls = @index / 2 == 0 ? "odd" : "even";
                                    <tr role="row" class="@rowCls">
                                        <td>@index</td>
                                        <td>@itDiet.Diet</td>
                                        <td>@itDiet.Calories</td>
                                        <td class="smart-form">
                                            <label class="checkbox">
                                                <input name="BreakFast" checked="checked" type="checkbox" value="@itDiet.Id">
                                                <i></i>
                                            </label>
                                        </td>
                                    </tr>
                                    index++;
                                }
                                index = 1;

                            }

                        }


                    </tbody>
                </table>
        </div>
    </div>
</div>

When I check my post method in Visual Studio I can see that I just receive the active page selected row with checkbox. Can you help me to improve my jquery code ?

UPDATE If you want know where is datatables source : DataTables And you may need to add this script to page

    <script src="~/Scripts/plugin/datatables/jquery.dataTables.min.js"></script>
    <script src="~/Scripts/plugin/datatables/dataTables.colVis.min.js"></script>
    <script src="~/Scripts/plugin/datatables/dataTables.tableTools.min.js"></script>
    <script src="~/Scripts/plugin/datatables/dataTables.bootstrap.min.js"></script>
    <script src="~/Scripts/plugin/datatable-responsive/datatables.responsive.min.js"></script>
    <script src="~/Scripts/jquery.formautofill.js"></script>
5
  • First of all, you have alot of errors in your code that you posted so please fix those so that we can see the problem. Commented May 27, 2019 at 13:14
  • @MelissaSkywalkz thanks for response , Please check datatables site for more detail ... Commented May 27, 2019 at 13:38
  • I still get some errors like: "Uncaught SyntaxError: Unexpected end of input" Commented May 27, 2019 at 13:40
  • My code contain razor syntax my be it cause problem ! Commented May 27, 2019 at 13:45
  • Possible duplicate of Store selected rows id Commented May 27, 2019 at 13:46

1 Answer 1

0

Here is Live example for jquery datatable with multi-select checkbox

and for getting selected Ids use this code

table.rows({ selected: true }).data().toArray().map(function (item) { return item.id; })

and here is code of the live example in case it no longer works

HTML

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
        <link rel="stylesheet" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
        <link rel="stylesheet" href="https://cdn.datatables.net/select/1.2.7/css/select.dataTables.min.css">
    
  </head>
  <body>
    <div class="container">
      <table id="example" class="display nowrap" width="100%">
    <thead>
        <tr>
          <th style="text-align: center"><input type="checkbox" id="select_all" /></th>
          <th>ID</th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td/>
          <td>1</td>
            <td>Tiger Nixon</td>
            <td>System Architect</td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$320,800</td>
        </tr>
        <tr>
                      <td/>

            <td>2</td>
            <td>Garrett Winters</td>
            <td>Accountant</td>
            <td>Tokyo</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$170,750</td>
        </tr>

    </tbody>
    <tfoot>
        <tr>
            <th></th>
            <th>ID</th>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
        </tr>
    </tfoot>
      </table>
      
        <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
        <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
        <script src="https://cdn.datatables.net/1.10.19/js/dataTables.bootstrap.min.js"></script>
        <script src="https://cdn.datatables.net/select/1.2.7/js/dataTables.select.min.js"></script>
          
      
    </div>
  </body>
</html>

JavaScript

$(document).ready(function() {
            
                table = $('#example').DataTable( {
                    columnDefs: [ {
                targets: 0,
                data: null,
                defaultContent: '',
                orderable: false,
                className: 'select-checkbox',
                    },
                                 {
                                 targets:1,
                                 visible: false}],
                    select: {
                        style:    'multi',
                        selector: 'td:first-child'
                    },
                    order: [[ 1, 'asc' ]]
                });
                
                $('#example').on('click', '#select_all', function () {
                    if ($('#select_all:checked').val() === 'on')
                        table.rows().select();
                    else
                        table.rows().deselect();
                });     
              
              $('#example tbody').on('click', 'tr td:first-child', function () {
                console.log(table.cell(this).render());
                console.log(table.row($(this).closest('tr')).data());
              });
              
           
            });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.