I'm reading a lot about this, the solution is always the same first fill the table and then call Datatable, but I can't get it to work for me, my problem is that it fills the table but Datatable doesn't recognize it, when writing to the box search the rows disappear and do not load again unless you refresh the browser
I tried to fill the table in different ways, I always get the same result.
How should I call Datatable to recognize the rows?
This is part of my code.
const DOMitems = document.querySelector('#items');
const productsUrl = 'http://localhost:5000/listproducts'
let fetchProducts = async () => {
const response = await fetch(productsUrl);
if (response.status !== 200) {
throw new Error("cannot fetch data");
}
let datashops = response.json();
return datashops;
};
function renderizarProductos() {
fetchProducts()
.then((datashop)=> {
datashop.forEach((item) => {
// Estructura
const miNodo = document.createElement('tr');
miNodo.classList.add('text-info');
const miNodoCardBody = document.createElement('td');
// Titulo
const miNodoTitle = document.createElement('td');
miNodoTitle.innerHTML += item.code_name;
// Imagen
const miNodoimg = document.createElement('td');
const miNodoImagen = document.createElement('img');
miNodoImagen.classList.add('img-fluid');
miNodoImagen.setAttribute('src', '/images/products/'+item.image);
// Precio
const miNodoPrecio = document.createElement('td');
/* miNodoPrecio.classList.add('card-text'); */
miNodoPrecio.innerHTML += (parseFloat(item.price.$numberDecimal)).toFixed(2);
const miNodoStock = document.createElement('td');
miNodoStock.innerHTML += item.stock;
// Boton
const miNodoBtn = document.createElement('td');
const miNodoBoton = document.createElement('button');
miNodoBoton.classList.add('btn', 'btn-primary');
miNodoBoton.innerHTML += '+';
miNodoBoton.setAttribute('marcador', item._id);
miNodoBoton.addEventListener('click', addProductsToCar);
// Insertamos
miNodo.appendChild(miNodoTitle);
miNodo.appendChild(miNodoPrecio);
miNodo.appendChild(miNodoStock);
/* miNodoimg.appendChild(miNodoImagen); */
/* miNodo.appendChild(miNodoimg); */
miNodoBtn.appendChild(miNodoBoton);
miNodo.appendChild(miNodoBtn);
DOMitems.appendChild(miNodo);
});
});
$('#sellproducts').DataTable();
}
renderizarProductos();
html showing datable
<table id="sellproducts" class="table" style="width:100%">
<thead>
<tr class="text-dark">
<th>Producto</th>
<th>precio</th>
<th>Stock</th>
<th>add</i></th>
</tr>
</thead>
<tbody id="items">
</tbody>
<tfoot>
<tr class="text-dark">
<th>Producto</th>
<th>precio</th>
<th>Stock</th>
<td>add</i></td>
</tr>
</tfoot>
</table>