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

如何用JavaScript实现表格动态编辑删除按钮及数据回显等功能?

Solution for Your HTML5 Form & Table CRUD Functionality

Hey there! Let's get your form and table working with all the required CRUD (Create/Read/Update/Delete) functionality. Your existing code had a few gaps like lost data on submit, static IDs, and missing edit/delete logic—let's fix that step by step.

First, here's the full revised code that implements all your requirements, followed by a breakdown of each feature:

Complete Working Code

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <style>
        .form {
            display: inline;
            width: 20%;
            padding: 6px 12px;
            font-size: 14px;
            line-height: 1.42857143;
            color: #555;
            background-color: #fff;
            border: 1px solid #ccc;
            border-radius: 4px;
        }
        #submit { text-align: center; }
        .button { position: absolute; }
    </style>
</head>
<body>
<div class="container">
    <center><h1> Fill This Form </h1></center>
    <p id='error' align="center"></p>
    <form id='myForm'>
        <div align="center" class="form-group">
            <label for="firstName">First-Name:- </label>
            <input type="text" class="form" id='firstName'>
        </div>
        <div align="center" class="form-group">
            <label for="lastName">Last-Name:- </label>
            <input type="text" class="form" id="lastName">
        </div>
        <div align="center" class="form-group">
            <label for="DOB"> DATE OF BIRTH:-</label>
            <input type="date" class="form" id="DOB">
            <span><input type="text" class="form" disabled></span>
        </div>
        <div align="center" class="form-group">
            <label for="image">Your Image </label>
            <input type="file" class="form" id="image" style="display:inline">
        </div>
        <div id="submit">
            <input type="button" id="button" value="submit">
        </div>
    </form>
</div>
<div class="container">
    <h2>Resulted Table</h2>
    <table id="list" class="table table-bordered">
        <thead>
            <tr>
                <th> ID </th>
                <th>Firstname</th>
                <th>Lastname</th>
                <th>Date Of Birth</th>
                <th> Image </th>
                <th> Actions </th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</div>

<script>
$(document).ready(function() {
    // Global variables to persist data and track edit mode
    let tableContaint = [];
    let currentEditId = null;

    // Render table with dynamic IDs and action buttons
    function renderTable() {
        $('#list tbody').empty();
        tableContaint.forEach((item, index) => {
            const row = `
                <tr>
                    <td>${index + 1}</td>
                    <td>${item.firstName}</td>
                    <td>${item.lastName}</td>
                    <td>${item.dob}</td>
                    <td>${item.image}</td>
                    <td>
                        <button class="btn btn-sm btn-primary edit-btn" data-id="${index}">Edit</button>
                        <button class="btn btn-sm btn-danger delete-btn" data-id="${index}">Delete</button>
                    </td>
                </tr>
            `;
            $('#list tbody').append(row);
        });
    }

    // Handle edit button clicks (event delegation for dynamic elements)
    $(document).on('click', '.edit-btn', function() {
        const id = $(this).data('id');
        currentEditId = id;
        const item = tableContaint[id];
        
        // Fill form with existing data
        $('#firstName').val(item.firstName);
        $('#lastName').val(item.lastName);
        $('#DOB').val(item.dob);
        $('#error').html('');
    });

    // Handle delete button clicks
    $(document).on('click', '.delete-btn', function() {
        const id = $(this).data('id');
        tableContaint.splice(id, 1);
        renderTable();
        $('#error').html('Record deleted successfully!').css('color', 'green');
    });

    // Submit button logic (add or update)
    $('#button').click(function() {
        // Validation
        if ($('#firstName').val() === '') {
            $('#error').html('Please fill the FirstName details.').css('color', 'red');
            return;
        } else if ($('#lastName').val() === '') {
            $('#error').html('Please fill the LastName details.').css('color', 'red');
            return;
        } else if ($('#DOB').val() === '') {
            $('#error').html('Please fill the date of birth details.').css('color', 'red');
            return;
        } else if ($('#image').val() === '' && currentEditId === null) {
            $('#error').html('Please upload the image').css('color', 'red');
            return;
        }

        $('#error').html('');
        const firstname = $('#firstName').val();
        const lastname = $('#lastName').val();
        const dob = $('#DOB').val();
        let imgName = '';

        // Get image name (keep existing for edits if no new image is uploaded)
        if ($('#image').val() !== '') {
            imgName = $('#image')[0].files[0].name;
        } else if (currentEditId !== null) {
            imgName = tableContaint[currentEditId].image;
        }

        const tableItem = { firstName: firstname, lastName: lastname, dob: dob, image: imgName };

        if (currentEditId === null) {
            // Add new record
            tableContaint.push(tableItem);
            $('#error').html('Record added successfully!').css('color', 'green');
        } else {
            // Update existing record
            tableContaint[currentEditId] = tableItem;
            $('#error').html('Record updated successfully!').css('color', 'green');
            currentEditId = null; // Reset to add mode
        }

        renderTable();
        $('#myForm')[0].reset();
    });
});
</script>
</body>
</html>

Key Feature Breakdown

1. Persistent Data Storage

I moved the tableContaint array to a global scope inside the ready function, so it doesn't get recreated every time you submit the form—your data will stay intact until the page refreshes.

2. Dynamic Table Rendering

The renderTable() function:

  • Clears existing table rows
  • Loops through your data array to generate new rows
  • Uses the array index + 1 as the dynamic ID (automatically updates when you delete records)
  • Adds unique edit/delete buttons with a data-id attribute to track which row corresponds to which array item

3. Edit Functionality

  • Uses event delegation (since buttons are dynamically generated) to handle edit clicks
  • Pulls the selected row's data from the array and fills the form fields
  • Tracks the current edit ID to distinguish between adding new records and updating existing ones
  • Skips re-requiring the image for edits (you can keep the existing image or upload a new one)

4. Delete Functionality

  • Also uses event delegation for delete buttons
  • Removes the selected item from the array with splice()
  • Re-renders the table immediately, so IDs automatically reorder to fill gaps

5. Submit Logic Updates

  • Modified validation to only require images for new records
  • Switches between "add" and "edit" mode based on currentEditId
  • Resets the form and updates the success/error message after each submission

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 04:53:06