Html Table With Bootstrap Jquery For Full Crud Operations

Create dynamic HTML tables with Bootstrap & jQuery for full CRUD operations. Enhance user experience with responsive designs and seamless interactions.

Transform Your Web Apps with Dynamic Tables and Smooth User Interactions

1. Intro

Ever looked at a slick website and thought "Man, I wish I could make something like that without spending hours coding"? Well, you're not alone! That's where HTML Tables with Bootstrap & jQuery come in handy. They let you create interactive data tables that look great and work smoothly across all devices.

In today's fast-paced online world, users expect websites to be quick and easy to use. An HTML table styled with Bootstrap makes your data look good on any screen size, while jQuery adds that interactive magic to make CRUD operations (Create, Read, Update, Delete) a breeze. Whether you're a seasoned pro or just starting out, mastering this combo can really level up your web dev skills.

So let's dive in and see how you can use Bootstrap and jQuery to create dynamic, responsive tables that handle full CRUD operations like a champ.

2. What are CRUD Operations?

Before we get our hands dirty with code, let's quickly go over what CRUD operations are and why they're so important for web apps.

CRUD stands for:

  • Create: Adding new stuff to your data
  • Read: Showing existing data
  • Update: Changing data that's already there
  • Delete: Getting rid of data you don't need anymore

Real-world examples:

  • Create: Signing up for a new account on a website
  • Read: Checking out a list of blog posts
  • Update: Editing your profile info
  • Delete: Removing an item from your shopping cart

These operations are the building blocks of interactive websites, letting users mess with content without having to reload the whole page. By using HTML tables to show data, Bootstrap to make it look good on any device, and jQuery to add interactivity, you can create a solid interface that handles CRUD operations smoothly.

3. Setting Up Your Dev Environment

Before we start coding, let's make sure you've got everything you need:

  • Code Editor: Pick one like Visual Studio Code, Sublime Text, or Atom
  • Web Browser: Chrome, Firefox, or Edge with dev tools
  • Bootstrap: A front-end framework that makes responsive design easier
  • jQuery: A JavaScript library that simplifies working with HTML

To include Bootstrap and jQuery, add these links to your HTML file's head section:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CRUD Operations with Bootstrap & jQuery</title>
  <!-- Bootstrap CSS -->
  <link
    href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    rel="stylesheet"
  >
</head>
<body>
  
  <!-- Your content goes here -->

  <!-- jQuery -->
  <script
    src="https://code.jquery.com/jquery-3.6.0.min.js"
  ></script>
  <!-- Bootstrap JS -->
  <script
    src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"
  ></script>
</body>
</html>

This setup gives you access to Bootstrap's styling and jQuery's functionality throughout your project.

4. Making Responsive HTML Tables with Bootstrap

Tables are a straightforward way to show structured data. But making them look good on all devices can be tricky. Bootstrap makes this easier with its built-in classes.

Here's a basic Bootstrap table:

<table class="table table-striped table-bordered">
  <thead class="table-dark">
    <tr>
      <th>#</th>
      <th>Name</th>
      <th>Email</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <!-- Dynamic Content Goes Here -->
  </tbody>
</table>

What these classes do:

  • table : Base class for Bootstrap tables
  • table-striped : Adds zebra-striping to rows
  • table-bordered : Adds borders to all sides
  • table-dark : Makes the header dark

To make sure the table looks good on all devices, wrap it in a .table-responsive container:

<div class="table-responsive">
  <table class="table table-striped table-bordered">
    <!-- Table Content -->
  </table>
</div>
Realistic scene in a modern office

This adds horizontal scroll on smaller screens so the table doesn't break the layout.

Here's a simple example of an HTML table using Bootstrap:

<div class="container mt-5">
  <h2>User Management</h2>
  <div class="table-responsive">
    <table class="table table-striped table-bordered" id="userTable">
      <thead class="table-dark">
        <tr>
          <th>#</th>
          <th>Name</th>
          <th>Email</th>
          <th>Actions</th>
        </tr>
      </thead>
      <tbody>
        <!-- Sample Data -->
        <tr>
          <td>1</td>
          <td>Jane Doe</td>
          <td>[email protected]</td>
          <td>
            <button class="btn btn-primary btn-sm edit-btn">Edit</button>
            <button class="btn btn-danger btn-sm delete-btn">Delete</button>
          </td>
        </tr>
        <!-- More Rows -->
      </tbody>
    </table>
  </div>
</div>
Realistic scene in a coworking space

You can add more styles to your table with Bootstrap classes. For example, adding table-hover will highlight rows when you mouse over them:

<table class="table table-striped table-bordered table-hover">
  <!-- Table Content -->
</table>

5. Adding CRUD Operations Using jQuery

Now that your table is set up, let's make it interactive. We'll use jQuery to handle CRUD operations so users can add, view, update, and delete data without reloading the page.

5.1. Create (Add) Operation

Goal: Let users add new entries to the table.

Steps:

  1. Add an 'Add' Button:
<button class="btn btn-success mb-3" id="addUserBtn">Add User</button>
  1. Create a Modal for Input:
<!-- Add User Modal -->
<div class="modal fade" id="addUserModal" tabindex="-1" aria-labelledby="addUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="addUserModalLabel">Add New User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="addUserForm">
          <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>
          <button type="submit" class="btn btn-primary">Add User</button>
        </form>
      </div>
    </div>
  </div>
</div>
  1. jQuery to Handle Form Submission:
$(document).ready(function(){
  // Show Add User Modal
  $('#addUserBtn').click(function(){
    $('#addUserModal').modal('show');
  });

  // Handle Add User Form Submission
  $('#addUserForm').submit(function(event){
    event.preventDefault();
    var name = $('#userName').val();
    var email = $('#userEmail').val();

    // Add new row to the table
    var newRow = `
      <tr>
        <td>${$('#userTable tbody tr').length + 1}</td>
        <td>${name}</td>
        <td>${email}</td>
        <td>
          <button class="btn btn-primary btn-sm edit-btn">Edit</button>
          <button class="btn btn-danger btn-sm delete-btn">Delete</button>
        </td>
      </tr>
    `;
    $('#userTable tbody').append(newRow);

    // Hide the modal
    $('#addUserModal').modal('hide');

    // Reset the form
    $('#addUserForm')[0].reset();
  });
});

How it works:

  • When you click "Add User", the modal pops up
  • When you submit the form, it grabs the new user data, makes a new row, and adds it to the table
  • Then it hides the modal and resets the form for next time

5.2. Read (View) Operation

Goal: Show data in an organized way so users can see existing entries.

Steps:

  1. Add a Detailed View Modal:
<!-- View User Modal -->
<div class="modal fade" id="viewUserModal" tabindex="-1" aria-labelledby="viewUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="viewUserModalLabel">User Details</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <p><strong>Name:</strong> <span id="viewName"></span></p>
        <p><strong>Email:</strong> <span id="viewEmail"></span></p>
      </div>
    </div>
  </div>
</div>
  1. Add View Button in Actions:
<button class="btn btn-info btn-sm view-btn">View</button>
  1. jQuery to Handle View Operation:
// Handle View Button Click
$(document).on('click', '.view-btn', function(){
  var currentRow = $(this).closest('tr');
  var name = currentRow.find('td:eq(1)').text();
  var email = currentRow.find('td:eq(2)').text();

  $('#viewName').text(name);
  $('#viewEmail').text(email);

  $('#viewUserModal').modal('show');
});

How it works:

  • Each row gets a "View" button
  • When clicked, it grabs the data from that row and shows it in a modal
  • This gives a quick, detailed view of the user without cluttering the table

5.3. Update (Edit) Operation

Goal: Let users change existing data entries.

Steps:

  1. Add an 'Edit' Button:
<button class="btn btn-primary btn-sm edit-btn">Edit</button>
  1. Create an Edit Modal:
<!-- Edit User Modal -->
<div class="modal fade" id="editUserModal" tabindex="-1" aria-labelledby="editUserModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="editUserModalLabel">Edit User</h5>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
      </div>
      <div class="modal-body">
        <form id="editUserForm">
          <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>
          <button type="submit" class="btn btn-primary">Update User</button>
        </form>
      </div>
    </div>
  </div>
</div>
  1. jQuery to Handle Edit Operation:
// Handle Edit Button Click
$(document).on('click', '.edit-btn', function(){
  var currentRow = $(this).closest('tr');
  var userId = currentRow.find('td:eq(0)').text();
  var userName = currentRow.find('td:eq(1)').text();
  var userEmail = currentRow.find('td:eq(2)').text();

  $('#editUserId').val(userId);
  $('#editUserName').val(userName);
  $('#editUserEmail').val(userEmail);

  $('#editUserModal').modal('show');
});

// Handle Edit User Form Submission
$('#editUserForm').submit(function(event){
  event.preventDefault();
  var userId = $('#editUserId').val();
  var userName = $('#editUserName').val();
  var userEmail = $('#editUserEmail').val();

  // Find the row to update
  $('#userTable tbody tr').each(function(){
    var currentRow = $(this);
    var currentId = currentRow.find('td:eq(0)').text();
    if(currentId == userId){
      currentRow.find('td:eq(1)').text(userName);
      currentRow.find('td:eq(2)').text(userEmail);
    }
  });

  // Hide the modal
  $('#editUserModal').modal('hide');
});

How it works:

  • Clicking "Edit" grabs the current data from the row and fills in the edit modal
  • When you submit, it finds the specific row using the user ID and updates the cells
  • This makes sure the table shows the latest data without needing to reload the page

5.4. Delete (Remove) Operation

Goal: Let users remove data entries from the table.

Steps:

  1. Add a 'Delete' Button:
<button class="btn btn-danger btn-sm delete-btn">Delete</button>
  1. jQuery to Handle Delete Operation:
// Handle Delete Button Click
$(document).on('click', '.delete-btn', function(){
  if(confirm("Are you sure you want to delete this user?")){
    $(this).closest('tr').remove();
    // Optionally, re-index the ID column
    $('#userTable tbody tr').each(function(index){
      $(this).find('td:eq(0)').text(index + 1);
    });
  }
});

How it works:

  • When you click "Delete", it asks if you're sure
  • If you say yes, it removes that row from the table
  • Then it updates the user IDs to keep everything in order

6. Hooking Up Backend Services

While the above setup handles CRUD operations on the front-end, real-world apps need to store data somewhere. Connecting to backend services makes sure data sticks around between sessions and users.

6.1. Connecting to APIs

To do CRUD operations with a backend, you'll usually work with RESTful APIs. Here's a quick rundown:

  • Create: POST request to add new data
  • Read: GET request to fetch data
  • Update: PUT or PATCH request to change data
  • Delete: DELETE request to remove data

Example: Using JSON Server for Mock APIs

JSON Server is an easy way to set up a fake REST API for testing.

  1. Install it:
npm install -g json-server
  1. Make a db.json file:
{
  "users": [
    { "id": 1, "name": "Jane Doe", "email": "[email protected]" }
  ]
}
  1. Run JSON Server:
json-server --watch db.json

Now you've got an API at http://localhost:3000/users .

6.2. Handling Data Storage

With the backend ready, let's tweak the jQuery code to talk to the API:

Example: Creating a User with AJAX

// Handle Add User Form Submission with Backend
$('#addUserForm').submit(function(event){
  event.preventDefault();
  var name = $('#userName').val();
  var email = $('#userEmail').val();

  $.ajax({
    url: 'http://localhost:3000/users',
    method: 'POST',
    data: { name: name, email: email },
    success: function(data){
      var newRow = `
        <tr>
          <td>${data.id}</td>
          <td>${data.name}</td>
          <td>${data.email}</td>
          <td>
            <button class="btn btn-info btn-sm view-btn">View</button>
            <button class="btn btn-primary btn-sm edit-btn">Edit</button>
            <button class="btn btn-danger btn-sm delete-btn">Delete</button>
          </td>
        </tr>
      `;
      $('#userTable tbody').append(newRow);
      $('#addUserModal').modal('hide');
      $('#addUserForm')[0].reset();
    },
    error: function(){
      alert('Error adding user.');
    }
  });
});

How it works:

  • When adding a user, it sends a POST request to the backend
  • If it works, it adds the new user to the table with the ID from the server
  • You can do similar things for Read, Update, and Delete to work with the backend

Tips:

  • Always handle errors nicely to let users know if something goes wrong
  • Show loading indicators so users know when stuff is happening
  • Make sure your API endpoints are secure, especially with sensitive data

7. Improving User Experience

A smooth user experience can make or break your web app. Here's how to make your CRUD tables even better for users.

7.1. Form Validation and Error Handling

Make sure data is correct and handle errors nicely.

HTML5 has some built-in validation:

<input type="email" class="form-control" id="userEmail" required>

For more complex checks, use jQuery:

if(!validateEmail(email)){
  alert('Please enter a valid email address.');
  return;
}

Always give feedback when things go wrong with AJAX:

<!-- Handle Add User Form Submission with Backend -->
$.ajax({
  // ...
  error: function(jqXHR, textStatus, errorThrown){
    alert(`Error: ${textStatus}`);
  }
});

7.2. User-Friendly Interfaces

Make your design easy to use.

  • Keep layouts consistent across modals and buttons
  • Use clear labels for form fields and buttons
  • Make sure your app works with keyboard and screen readers

7.3. Real-Time Updates and Notifications

Let users know when things happen or if there are errors.

Success messages:

alert('User added successfully!');

Or for a nicer look, use Bootstrap alerts:

$('#successAlert').show();

Loading indicators:

Show spinners while stuff is loading:

$('#loadingSpinner').show(); // To show
$('#loadingSpinner').hide(); // To hide

8. Speeding Things Up

As your app grows, making sure it stays fast becomes super important. Here's how to keep your tables quick and responsive.

8.1. Efficient DOM Changes

Changing the DOM a lot can slow things down. Optimize by:

  • Batch updates: Make multiple changes before adding to the DOM
var fragment = $(document.createDocumentFragment());
data.forEach(function(user){
  var row = `<tr>...</tr>`;
  fragment.append(row);
});
$('#userTable tbody').append(fragment);
  • Minimize reflows: Group DOM read and write operations separately

8.2. Reducing Reflows and Repaints

  • Use CSS classes instead of inline styles to reduce style recalculations
  • Store jQuery selectors in variables to avoid searching the DOM repeatedly
var $tableBody = $('#userTable tbody');
$tableBody.append(newRow);

8.3. Optimizing Data Loading

  • Pagination: Load and show a bit of data at a time to speed up initial loading
  • Lazy loading: Load data as needed, especially for big datasets
  • Virtual scrolling: Only show the part of the table that's visible, which helps with lots of data

9. Cool Extra Features

Take your CRUD tables to the next level with these advanced features.

9.2. Inline Editing

Let users edit table data right in the cells.

Steps:

  1. Make table cells editable:
<td class="editable">Jane Doe</td>

jQuery to handle inline editing:

// Make table cells editable on double-click
$(document).on('dblclick', '.editable', function(){
  var currentCell = $(this);
  var originalContent = currentCell.text();
  var input = $('', {
    type: 'text',
    value: originalContent,
    class: 'form-control'
  });
  currentCell.html(input);
  input.focus();

  // Handle input blur (loss of focus)
  input.blur(function(){
    var newContent = $(this).val();
    currentCell.text(newContent);
    // Optionally, send update to backend here
  });
});

How it works:

  • Double-clicking a cell turns it into an input field
  • When you click away, it saves the new content back to the cell
  • This makes editing super smooth without needing separate modals

9.3. Role-Based Access

Control who can do what based on user roles.

Scenario:

  • Admin: Can do everything
  • Editor: Can create and update but not delete
  • Viewer: Can only view

Steps:

  1. Define user roles:

    This should be handled by your backend and login system

  2. Control UI elements:

    Use jQuery to show or hide buttons based on the user's role

    var userRole = 'admin'; // This should come from your authentication system
    
    if(userRole === 'viewer'){
      $('.edit-btn, .delete-btn').hide();
    } else if(userRole === 'editor'){
      $('.delete-btn').hide();
    }
    
  3. Backend validation:

    Make sure your backend also checks permissions to prevent unauthorized actions

10. Fixing Common Problems

Every developer runs into issues. Here are some common ones and how to fix them:

10.2. Event Handlers Not Working on New Rows

Problem: "Edit" or "Delete" buttons on new rows don't work when clicked.

Fix:

Use event delegation instead of binding directly to elements:

$(document).on('click', '.edit-btn', function(){
  // Handler code
});

10.3. Data Disappearing After Refresh

Problem: Added users vanish when you reload the page.

Fix:

  • If you're just changing the DOM, data won't stick around
  • Use AJAX to send and get data from a backend or mock server
  • For simpler apps, you could use localStorage to save data on the client side

10.4. Table Looks Weird on Mobile

Problem: Table layout breaks on small screens.

Fix:

  • Make sure you're using the .table-responsive wrapper
  • Consider hiding less important columns on small screens using Bootstrap's responsive utilities
  • Test on different devices and adjust as needed

12. Wrapping Up

Learning how to create dynamic, responsive HTML tables with Bootstrap and jQuery opens up a world of possibilities for your web apps. By mastering CRUD operations, you're giving your projects the tools they need to manage data and interact with users - which is super important for interactive websites.

From setting up your development environment to connecting with backend services and making things user-friendly, each step plays a big role in creating smooth-running applications. While newer frameworks keep popping up, the basic skills of HTML, Bootstrap, and jQuery are still really valuable, offering a simple and efficient way to build all kinds of projects.

Ready to Level Up Your Web Dev Skills?

Don't let your tables just sit there showing static data. Make them interactive, responsive, and functional in ways users will love. Dive into your next project knowing that with Bootstrap and jQuery, you've got all the CRUD operations at your fingertips.

Get Started Today! Try out the examples we've covered, tweak them to fit what you need, and watch your web apps transform into dynamic, user-friendly experiences.

Happy Coding!

Understanding CRUD Operations

Building Responsive Tables with Bootstrap

Convert an image to HTML

All blog posts