Question
Answer and Explanation
Yes, there are many UI data table examples that include a "no data" message. These are crucial for providing a good user experience when a table is empty. Here's how you can implement one using HTML, CSS, and a bit of JavaScript:
HTML Structure:
First, create a basic HTML table structure. Include a placeholder for the "no data" message within the table container.
<div class="table-container">
<table id="data-table">
<thead>
<tr>
<th>Name</th>
<th>Age</th>
<th>City</th>
</tr>
</thead>
<tbody id="table-body">
</tbody>
</table>
<div id="no-data-message" class="no-data-message" style="display: none;">
<p>No data available.</p>
</div>
</div>
JavaScript Logic:
Use JavaScript to check if the table has any data. If not, display the "no data" message and hide the table headers.
document.addEventListener("DOMContentLoaded", function() {
const tableBody = document.getElementById("table-body");
const noDataMessage = document.getElementById("no-data-message");
const table = document.getElementById("data-table");
function checkTableData() {
if (tableBody.children.length === 0) {
noDataMessage.style.display = "block";
table.style.display = "none";
} else {
noDataMessage.style.display = "none";
table.style.display = "table";
}
}
// Example: Simulate data loading (replace with your actual data)
const data = []; // Or your actual data array
if (data.length > 0) {
data.forEach(item => {
const row = tableBody.insertRow();
const nameCell = row.insertCell();
const ageCell = row.insertCell();
const cityCell = row.insertCell();
nameCell.textContent = item.name;
ageCell.textContent = item.age;
cityCell.textContent = item.city;
});
}
checkTableData();
});
CSS Styling:
Add some basic CSS to style the table and the "no data" message.
.table-container {
width: 100%;
overflow-x: auto;
}
#data-table {
width: 100%;
border-collapse: collapse;
}
#data-table th, #data-table td {
border: 1px solid #ddd;
padding: 8px;
text-align: left;
}
#data-table th {
background-color: #f2f2f2;
}
.no-data-message {
text-align: center;
padding: 20px;
color: #888;
}
This example provides a basic implementation. You can customize the styling and logic to fit your specific needs. Remember to replace the example data loading with your actual data source.