do not show datatable when there is not any content
do not show datatable when there is not any content
bibalani
Posts: 14Questions: 3Answers: 0
Hi,
I wanna disappear table when there is not any content. can you help me fix it
.html
{% extends 'my_app/base.html' %}
{% block body_block %}
{% load static %}
{% load crispy_forms_tags %}
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css"
integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<link rel="stylesheet" href="{% static 'my_app/style.css' %}">
</head>
<div class="form-group">
<form id="product_form" data-url="{% url 'my_app:add_product' %}">
{% for field in product_form %}
<label class="order-label" for="{{ field.auto_id }}">{{ field.label }}</label>
{{ field }}
{% endfor %}
{% csrf_token %}
<br>
<input class="btn btn-block" type="submit" value="Submit Product" style="width:600px">
</form>
<br>
</div>
<table id="current_product" class="display" style="width:100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Produced Date</th>
<th>Expired Date</th>
<th>Company</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
{% endblock %}
.js
$(document).ready(function(){
$('#product_form').submit(function(e){
e.preventDefault();
var serializedData = $(this).serialize();
var url = document.querySelector('#product_form').dataset.url
$.ajax({
type: 'POST',
url: url,
data: serializedData,
success: function(response){
$('#product_form').trigger('reset');
// var ser_user_product = JSON.parse(response['ser_user_product']);
// var user_product_fields = ser_user_product[0]['fields'];
var product_fields = response['ser_product']
$('#current_product tbody').append(
`<tr>
<td>${product_fields["id"]||""}</td>
<td>${product_fields["name"]||""}</td>
<td>${product_fields["produced_date"]||""}</td>
<td>${product_fields["expired_date"]||""}</td>
<td>${product_fields["company"]||""}</td>
</tr>`
)
$('#current_product').DataTable();
},
});
});
});
This question has an accepted answers - jump to answer
Answers
This uses bootstrap 3 class "hidden" but you can use other css as well.
Of course you can also do it outside the api in case you assigned an id to the container div of your Data Table in your HTML:
You might want to use the "draw" event instead of the "init" event.