Bootstrap Html Table With Crud Functionality

Create dynamic web apps with a Bootstrap HTML table featuring CRUD functionality. Learn to display, edit, and manage data effortlessly and user-friendly.

Intro

Ever stared at your screen thinking, "How the heck do I make this data look good?" Maybe you're building a dashboard or just want to show some info without it looking like a mess. Well, here's where Bootstrap HTML Tables with CRUD come in handy. It's like the Swiss Army knife of data display - looks great and lets you mess with the data easily.

Picture a table that's not just pretty but also lets you add, view, change, and delete stuff without breaking a sweat. Sounds awesome, right? With Bootstrap and a bit of JavaScript magic, you can make it happen. Let's dive in and see why this combo is so cool and how to use it in your projects.

a clean office desk setup

Getting Started with Bootstrap Tables

Setting Up Your Stuff

Before we jump in, let's make sure we've got everything we need. If you're new to Bootstrap, don't sweat it - it's super easy to get going.

  1. Get Bootstrap in Your Project: You can download it or use a CDN. Here's the quick way with CDN:
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  2. Set Up Your HTML: Make a basic HTML file and stick the Bootstrap links in the <head> part.
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Bootstrap CRUD Table</title>
        <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body>
        <!-- Your stuff goes here -->
        <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
    </body>
    </html>

Basic Structure of a Bootstrap Table

Bootstrap tables look clean and work on all devices. Let's start with a simple one.

<div class="container mt-5">
    <h2 class="mb-4">User Management</h2>
    <table class="table table-striped">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Actions</th>
            </tr>
        </thead>
        <tbody>
            <!-- Table rows go here -->
            <tr>
                <td>1</td>
                <td>Jane Doe</td>
                <td>[email protected]</td>
                <td>
                    <button class="btn btn-primary btn-sm">Edit</button>
                    <button class="btn btn-danger btn-sm">Delete</button>
                </td>
            </tr>
        </tbody>
    </table>
</div>

Pretty neat, huh? But hold on, this is just the start. Let's make this table do some cool stuff.

a computer screen displaying a Bootstrap table

What's CRUD All About?

What is CRUD?

CRUD stands for Create, Read, Update, and Delete - the four main things you do with data in most apps. Think of it like this: if your data is a pizza, CRUD is how you make it, serve it, change the toppings, and eventually toss it out.

Why CRUD Matters in Web Apps

CRUD is super important because it's the backbone of most web apps. Whether you're dealing with user accounts, product lists, or blog posts, CRUD is everywhere. Getting these operations right makes your app solid, easy to use, and able to grow.

Making CRUD Work

Alright, enough talk. Let's roll up our sleeves and make CRUD happen in our Bootstrap table. We'll use JavaScript to make it interactive. To keep things simple, we'll handle the data on the client side, but the same ideas work when you're dealing with a backend too.

Creating Data (Create)

First up, let's add a form to create new entries.

<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="addUserForm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Add New User</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <div class="mb-3">
              <label for="userName" class="form-label">Name</label>
              <input type="text" class="form-control" id="userName" required>
          </div>
          <div class="mb-3">
              <label for="userEmail" class="form-label">Email</label>
              <input type="email" class="form-control" id="userEmail" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Add User</button>
        </div>
      </div>
    </form>
  </div>
</div>

Isn't it cool how Bootstrap makes modals so easy? Now, let's add a button to pop up this modal.

<button class="btn btn-success mb-3" data-bs-toggle="modal" data-bs-target="#addUserModal">Add New User</button>

Now, we need to handle the form submission with JavaScript.

let users = [];
let userId = 1;

document.getElementById('addUserForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const name = document.getElementById('userName').value;
    const email = document.getElementById('userEmail').value;
    users.push({ id: userId++, name, email });
    renderTable();
    this.reset();
    new bootstrap.Modal(document.getElementById('addUserModal')).hide();
});

Reading Data (Read)

Reading data is all about showing it in your table. We need a function to put the rows in the table based on our users array.

function renderTable() {
    const tbody = document.querySelector('table tbody');
    tbody.innerHTML = '';
    users.forEach(user => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${user.id}</td>
            <td>${user.name}</td>
            <td>${user.email}</td>
            <td>
                <button class="btn btn-primary btn-sm me-2" onclick="editUser(${user.id})">Edit</button>
                <button class="btn btn-danger btn-sm" onclick="deleteUser(${user.id})">Delete</button>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

Easy, right? Whenever our users array changes, calling renderTable() will update what's shown.

Updating Data (Update)

Editing a user needs another modal similar to the add user form. Let's set that up.

<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserLabel" aria-hidden="true">
  <div class="modal-dialog">
    <form id="editUserForm">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title">Edit User</h5>
          <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
        </div>
        <div class="modal-body">
          <input type="hidden" id="editUserId">
          <div class="mb-3">
              <label for="editUserName" class="form-label">Name</label>
              <input type="text" class="form-control" id="editUserName" required>
          </div>
          <div class="mb-3">
              <label for="editUserEmail" class="form-label">Email</label>
              <input type="email" class="form-control" id="editUserEmail" required>
          </div>
        </div>
        <div class="modal-footer">
          <button type="submit" class="btn btn-primary">Save Changes</button>
        </div>
      </div>
    </form>
  </div>
</div>

Now, let's make the editUser function and handle the form submission.

function editUser(id) {
    const user = users.find(u => u.id === id);
    if (!user) return;
    document.getElementById('editUserId').value = user.id;
    document.getElementById('editUserName').value = user.name;
    document.getElementById('editUserEmail').value = user.email;
    new bootstrap.Modal(document.getElementById('editUserModal')).show();
}

document.getElementById('editUserForm').addEventListener('submit', function(e) {
    e.preventDefault();
    const id = parseInt(document.getElementById('editUserId').value);
    const name = document.getElementById('editUserName').value;
    const email = document.getElementById('editUserEmail').value;
    const userIndex = users.findIndex(u => u.id === id);
    if (userIndex !== -1) {
        users[userIndex].name = name;
        users[userIndex].email = email;
        renderTable();
        this.reset();
        new bootstrap.Modal(document.getElementById('editUserModal')).hide();
    }
});

Deleting Data (Delete)

Finally, let's add the ability to delete a user.

function deleteUser(id) {
    if (confirm('You sure you wanna delete this user?')) {
        users = users.filter(u => u.id !== id);
        renderTable();
    }
}

And just like that, you've got a fully working CRUD table using Bootstrap and plain old JavaScript! Pretty cool, right?

Making It User-Friendly

Responsive Design with Bootstrap

One of the best things about Bootstrap is how it makes stuff look good on any device. Your table will look great whether it's on a big computer screen or a tiny phone. The .table-responsive class can wrap your table to make it scroll sideways on smaller screens.

<div class="table-responsive">
    <table class="table table-striped">
        <!-- Table stuff -->
    </table>
</div>

User-Friendly Interfaces

Making your table easy to use is more than just making it look pretty. Think about adding stuff like:

  • Clear Buttons: Make buttons easy to spot with colors and icons.
  • Feedback: Let users know when they've done something right or if something went wrong.
  • Accessible Design: Make sure people can use your table with just a keyboard or screen readers.

Hooking It Up to the Backend

So far, we've been handling data on the client side. But what if you need to save data or share it between users? This is where backend stuff comes in handy.

Connecting to APIs

To connect your table with a backend, you can use AJAX to talk to APIs. Here's a simple example using Fetch API:

// Get data from the server
fetch('https://api.example.com/users')
    .then(response => response.json())
    .then(data => {
        users = data;
        renderTable();
    })
    .catch(error => console.error('Oops:', error));

// Add a new user to the server
document.getElementById('addUserForm').addEventListener('submit', function(e) {
    // Previous code...
    fetch('https://api.example.com/users', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ name, email })
    })
    .then(response => response.json())
    .then(data => {
        users.push(data);
        renderTable();
        // Rest of the code...
    })
    .catch(error => console.error('Oops:', error));
});

Handling Data Persistence

Backend services make sure your data sticks around and can be accessed from different devices. Whether you're using RESTful APIs, GraphQL, or real-time databases, hooking your Bootstrap table up to a solid backend is key for apps that can grow.

You can try this feature yourself at img2html.com .

Cool Extra Features

Pagination and Sorting

As your data gets bigger, loading everything at once can slow things down. Adding pagination and sorting can make your app faster and easier to use.

Pagination Example:

let currentPage = 1;
const rowsPerPage = 5;

function renderTable() {
    const tbody = document.querySelector('table tbody');
    tbody.innerHTML = '';
    const start = (currentPage - 1) * rowsPerPage;
    const end = start + rowsPerPage;
    users.slice(start, end).forEach(user => {
        // Create table rows
    });
    renderPagination();
}

function renderPagination() {
    const totalPages = Math.ceil(users.length / rowsPerPage);
    const pagination = document.getElementById('pagination');
    pagination.innerHTML = '';
    for (let i = 1; i <= totalPages; i++) {
        const li = document.createElement('li');
        li.classList.add('page-item', i === currentPage ? 'active' : '');
        li.innerHTML = `${i}`;
        li.addEventListener('click', () => {
            currentPage = i;
            renderTable();
        });
        pagination.appendChild(li);
    }
}

Sorting Example:

function sortTable(column) {
    users.sort((a, b) => {
        if (a[column] < b[column]) return -1;
        if (a[column] > b[column]) return 1;
        return 0;
    });
    renderTable();
}

Add clickable headers to start sorting:

<th onclick="sortTable('name')">Name</th>
<th onclick="sortTable('email')">Email</th>

Search Functionality

Searching lets users find specific data quickly. Here's a simple search setup:

<input type="text" id="searchInput" class="form-control mb-3" placeholder="Search...">

<script>
document.getElementById('searchInput').addEventListener('input', function() {
    const query = this.value.toLowerCase();
    const filteredUsers = users.filter(user => 
        user.name.toLowerCase().includes(query) ||
        user.email.toLowerCase().includes(query)
    );
    renderFilteredTable(filteredUsers);
});

function renderFilteredTable(filteredUsers) {
    const tbody = document.querySelector('table tbody');
    tbody.innerHTML = '';
    filteredUsers.forEach(user => {
        // Create table rows
    });
}
</script>

Validation and Error Handling

Making sure your data is correct is super important. Add checks on both the client and server side to stop wrong data from getting in.

document.getElementById('addUserForm').addEventListener('submit', function(e) {
    // Previous code...
    if (!validateEmail(email)) {
        alert('Hey, that email doesn't look right.');
        return;
    }
    // Rest of the code...
});

function validateEmail(email) {
    const re = /^[^s@]+@[^s@]+.[^s@]+$/;
    return re.test(email);
}

Best Practices

Security Considerations

When you're doing CRUD stuff, especially with backends, security should be top of your list.

  • Clean Up Inputs: Stop SQL injection and XSS attacks by cleaning user inputs.
  • Check Who's Allowed: Make sure only the right people can do certain things.
  • Use HTTPS: Encrypt data when it's sent to keep sensitive stuff safe.

Code Organization

Keep your code clean and organized so it's easy to read and maintain.

  • Break It Up: Split your code into functions and modules.
  • Name Things Clearly: Use names for variables and functions that make sense.
  • Add Comments: Explain tricky parts of your code.

Wrapping It Up

Building a Bootstrap HTML Table with CRUD isn't just about making a table; it's about creating a cool, interactive way to handle data. Whether you're a pro developer or just starting out, adding these features can make your web apps way better.

Remember, Bootstrap handles the looks and responsiveness, while JavaScript brings the interactivity for CRUD operations. As you get more comfortable with these tools, you can explore even cooler features like real-time updates, complex checks, and smooth backend connections.

Ready to level up your web dev skills? Start building Bootstrap tables with CRUD today and watch your projects go from boring data displays to dynamic, user-friendly interfaces.

Happy coding, folks!

Convert an image to HTML

All blog posts