You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为动态生成的Bootstrap表格添加批量删除复选框?

Solution: Bootstrap Batch Delete with Flask + SQLite

Let's build this batch delete feature properly—here's a step-by-step implementation that fits your existing setup:

1. Updated Frontend (HTML Template)

First, we'll modify your Bootstrap table to add checkboxes, a "Delete Selected" button, and wrap everything in a form for submission. We'll also add a quick JavaScript snippet for a "Select All" checkbox to make the user experience smoother.

<!DOCTYPE html>
<html>
<head>
    <title>Leer Bootstrap</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"></script>
</head>
<body>
    <div class="container-fluid mt-4">
        <h3 class="display-6"><u>Registered Devices</u></h3>
        
        <!-- Batch Delete Form -->
        <form method="POST" action="/delete-devices" class="mb-3">
            <button type="submit" class="btn btn-danger">Delete Selected Devices</button>
            
            <div class="col-md-6 mt-3">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <!-- Select All Checkbox -->
                            <th scope="col" class="col-md-1">
                                <input type="checkbox" id="selectAll">
                            </th>
                            <th scope="col" class="col-md-5">Device Name</th>
                            <th scope="col" class="col-md-6">Device MAC</th>
                        </tr>
                    </thead>
                    <tbody>
                        {% for row in data %}
                        <tr>
                            <td>
                                <!-- Individual Device Checkbox (using MAC as unique identifier) -->
                                <input type="checkbox" name="selected_macs" value="{{ row[1] }}">
                            </td>
                            <td>{{ row[0] }}</td>
                            <td>{{ row[1] }}</td>
                        </tr>
                        {% endfor %}
                    </tbody>
                </table>
            </div>
        </form>
    </div>

    <!-- Select All Script -->
    <script>
        document.getElementById('selectAll').addEventListener('change', function() {
            const checkboxes = document.querySelectorAll('input[name="selected_macs"]');
            checkboxes.forEach(checkbox => checkbox.checked = this.checked);
        });
    </script>
</body>
</html>

Key Frontend Changes:

  • Wrapped the table in a form with POST method pointing to a new Flask route (/delete-devices)
  • Added a Select All checkbox in the header with a simple JS snippet to toggle all row checkboxes
  • Added individual checkboxes for each device, using the Device MAC (a unique identifier) as the value
  • Added a Bootstrap-styled delete button to trigger the batch delete

2. Flask Backend Updates

Next, update your Flask app to handle the batch delete request. We'll use SQLite's IN clause to delete multiple records at once safely.

from flask import Flask, render_template, request, redirect, url_for
import sqlite3

app = Flask(__name__)

# Helper function to connect to SQLite
def get_db_connection():
    conn = sqlite3.connect('your_database.db')  # Replace with your actual database filename
    conn.row_factory = sqlite3.Row
    return conn

# Route to display devices
@app.route('/')
def index():
    conn = get_db_connection()
    # Replace 'your_table_name' with the name of your devices table
    data = conn.execute('SELECT device_name, device_mac FROM your_table_name').fetchall()
    conn.close()
    return render_template('your_template.html', data=data)  # Replace with your template filename

# Route to handle batch delete
@app.route('/delete-devices', methods=['POST'])
def delete_devices():
    selected_macs = request.form.getlist('selected_macs')
    
    if selected_macs:
        conn = get_db_connection()
        # Use dynamic placeholders to avoid SQL injection
        placeholders = ', '.join('?' for _ in selected_macs)
        conn.execute(f'DELETE FROM your_table_name WHERE device_mac IN ({placeholders})', selected_macs)
        conn.commit()
        conn.close()
    
    # Redirect back to the devices page after deletion
    return redirect(url_for('index'))

if __name__ == '__main__':
    app.run(debug=True)

Key Backend Changes:

  • Created a new POST route (/delete-devices) to handle the form submission
  • Used request.form.getlist('selected_macs') to collect all checked MAC addresses
  • Used SQLite's IN clause with dynamic placeholders to safely delete multiple records (prevents SQL injection)
  • Redirects back to the devices list after deletion completes

3. Important Notes

  • Unique Identifier: We used Device MAC because it's unique (device names might not be). If your table uses a different unique ID (like an auto-incrementing id), use that instead for more reliable deletes.
  • SQL Injection Safety: The dynamic placeholders ensure we don't expose ourselves to SQL injection attacks—never directly concatenate user input into SQL queries.
  • Bootstrap Styling: The layout uses Bootstrap's container-fluid, mt-4, mb-3, and btn btn-danger classes to keep things responsive and consistent with your existing design.

This implementation is efficient, user-friendly, and fits perfectly with your current tech stack!

内容的提问来源于stack exchange,提问作者Wilmer Kluever

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 07:50:39