coder
coder

Reputation: 461

DataTables not sorting properly

I am using DataTables for my project but its sorting function does not work properly. I have tried every single solutions in here but none of them worked for me as well as it does not show the error in the console. I think in my code there is a jQuery conflict. How can I solve this issue? any help?

<table id="dtBasicExample" class="table table-bordered table-hover contact-list" cellspacing="0"
                       width="100%">
                    <thead>
                    <tr>
                        {#                            <th scope="col"><input type="checkbox"></th>#}
                        <th scope="col">Name</th>
                        <th scope="col">Company Name</th>
                        <th scope="col">Email</th>
                        <th scope="col">Phone Number</th>
                    </tr>
                    </thead>
                    {% for contact in contacts %}
                        <tbody>
                        <tr data-id="{{ contact.id }}" class="clickable-row"
                            data-href="{% url 'contact-detail' contact.id %}"
                            style="cursor: pointer; ">
                            {#                                <th scope="row"><input type="checkbox" id="check"></th>#}
                            <td>{{ contact.client_name }}</td>
                            <td>{{ contact.client_company_name }}</td>
                            <td>{{ contact.email }}</td>
                            <td>{{ contact.work_phone }}</td>
                        </tr>
                        </tbody>
                    {% endfor %}
                </table>
                {% csrf_token %}

$('#dtBasicExample').DataTable();
$('.dataTables_length').addClass('bs-select');

as you can see it is a material bootstrap design datatables. In the example shown it works but when i add to my project it does not.

Upvotes: 2

Views: 240

Answers (1)

R3tep
R3tep

Reputation: 12864

Your html table is "not valid" (It is valid if you want to create multiple table into an parent table). This can make some issue with Datatable. I think sorting is done, but you do not see it, because it sort by tbody tag and there is one line sorted by tbody. The tbody tags are not sorted only the tr inside

Try to remove the tbody into your loop and export it outside the for loop.

<tbody>
  {% for contact in contacts %}
  // ...
  {% endfor %}
</tbody>

Note: cellspacing="0" is an old version of html. You can replace it by the css property border-spacing

Upvotes: 3

Related Questions