user9888683
user9888683

Reputation:

sort for dataTable

I am trying to sort in datatable but, i couldn't understand how to do it. let me show what i tired to do with my code.

$(document).ready(function() {
            $('#table').DataTable();
        } );
<script src="//cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css">
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.18/css/jquery.dataTables.min.css" type="text/css" media="all" />

     <table  id="table" class="display" style="width:100%">
              <thead>
                        <tr>
                          <th>Stock</th>
                          <th>Rate</th>
                        </tr>
              </thead>

        @if($trades)
            @foreach($trades as $trade)

                  <tbody>
                    <tr>
                      <td>{{$trade->stock}}</td>
                      <td>{{$trade->rate}}</td>
                    </tr>
                  </tbody>
            @endforeach
        @endif

    </table>

I worked hard but unable to find what i have not done.

Upvotes: 1

Views: 83

Answers (1)

Bryan Miller
Bryan Miller

Reputation: 3323

I think you need to move your @foreach to be inside of your <tbody> like this:

             <tbody>
                @foreach($trades as $trade)
                <tr>
                  <td>{{$trade->stock}}</td>
                  <td>{{$trade->rate}}</td>
                </tr>
                @endforeach
             </tbody>

To get the sorting to work, you'll have to add an option to your javascript like this:

$(document).ready(function() {
    $('#table').DataTable( {
        "order": [[ 3, "desc" ]]
    } );
} );

Which will order your table by the 4th column (since the 3 in the above example starts counting indexes at 0) in descending order. Reference - https://datatables.net/examples/basic_init/table_sorting.html

Upvotes: 1

Related Questions