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

动态增删表单组并设置输入框唯一ID与Name的技术问题

Solution: Dynamic Form Groups with Unique Name/ID Attributes

Got it, let's work through this problem together. The core issue is generating unique name and id values for each dynamic form group so your PHP backend can correctly parse and save the data. Here's a step-by-step fix:

1. Fix the HTML Template (Add Placeholders)

First, update your hidden template to use placeholder values for name and id (like {index}). We'll replace this placeholder with a unique number each time we add a new group:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

<section> 
    <!-- Initial Form Group -->
    <div class="row fieldGroup"> 
        <div class="col-md-3"> 
            <div class="form-group"> 
                <label for="productId1">ID :</label> 
                <input type="text" name="productId1" class="form-control" id="productId1"> 
            </div> 
        </div> 
        <div class="col-md-5"> 
            <div class="form-group"> 
                <label for="productName1">Name :</label> 
                <!-- Fixed the typo here: was productId[], should be productName[] originally -->
                <input type="text" name="productName1" class="form-control" id="productName1"> 
            </div> 
        </div> 
        <div class="col-md-2"> 
            <div class="form-group"> 
                <label for="price1">Price :</label> 
                <input type="number" name="price1" id="price1" class="form-control"> 
            </div> 
        </div> 
        <div class="col-md-2"> 
            <div class="form-group"> 
                <label for="commission1">Commission :</label> 
                <input type="number" name="commission1" id="commission1" class="form-control"> 
            </div> 
        </div> 
        <a href="#" class="btn btn-success addMore"><span class="glyphicon glyphicon-plus" aria-hidden="true"></span> Add</a> 
    </div> 

    <!-- Hidden Template with Placeholders -->
    <div class="row fieldGroupCopy" style="display: none;"> 
        <div class="col-md-3"> 
            <div class="form-group"> 
                <label for="productId{index}">ID :</label> 
                <input type="text" name="productId{index}" class="form-control" id="productId{index}"> 
            </div> 
        </div> 
        <div class="col-md-5"> 
            <div class="form-group"> 
                <label for="productName{index}">Name :</label> 
                <input type="text" name="productName{index}" class="form-control" id="productName{index}"> 
            </div> 
        </div> 
        <div class="col-md-2"> 
            <div class="form-group"> 
                <label for="price{index}">Price :</label> 
                <input type="number" name="price{index}" id="price{index}" class="form-control"> 
            </div> 
        </div> 
        <div class="col-md-2"> 
            <div class="form-group"> 
                <label for="commission{index}">Commission :</label> 
                <input type="number" name="commission{index}" id="commission{index}" class="form-control"> 
            </div> 
        </div> 
        <a href="#" class="btn btn-danger remove"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span> Remove</a> 
    </div> 
</section>

2. Update jQuery to Generate Unique IDs/Names

Next, fix the jQuery selectors (you missed . for class selectors) and add logic to track the current group count, replacing the {index} placeholder with the next number:

$(document).ready(function() { 
    // Group add limit
    var maxGroup = 7; 
    // Track current group number (starts at 2 since we have 1 initial group)
    var currentGroup = 2;

    // Add more fields group
    $(".addMore").click(function(e) { 
        e.preventDefault(); // Prevent default link behavior
        if ($('body').find('.fieldGroup').length < maxGroup) { 
            // Get template HTML and replace {index} with currentGroup
            var fieldHTML = $('.fieldGroupCopy').html().replace(/{index}/g, currentGroup);
            // Wrap in fieldGroup div and append
            $('body').find('.fieldGroup:last').after('<div class="row fieldGroup">' + fieldHTML + '</div>');
            // Increment group number for next addition
            currentGroup++;
        } else { 
            alert('Maximum ' + maxGroup + ' groups are allowed.'); 
        } 
    }); 

    // Remove fields group
    $("body").on("click", ".remove", function(e) { 
        e.preventDefault();
        $(this).parents(".fieldGroup").remove(); 
        // Optional: If you want to re-number groups after deletion, you can add logic here
        // But for PHP processing, non-consecutive numbers are fine as long as each group's fields match
    }); 
}); 

3. PHP Backend to Process Submitted Data

Now, your PHP script can loop through the submitted fields by checking the highest group number, or collect all matching fields. Here's a simple example:

<?php
// Check if form is submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Initialize an array to hold all product data
    $products = [];

    // Find the highest group number (or loop until no more fields exist)
    $i = 1;
    while (isset($_POST["productId$i"])) {
        $products[] = [
            'product_id' => $_POST["productId$i"],
            'product_name' => $_POST["productName$i"],
            'price' => $_POST["price$i"],
            'commission' => $_POST["commission$i"]
        ];
        $i++;
    }

    // Now you can insert each product into your database
    // Example using PDO (adjust to your database setup)
    /*
    $pdo = new PDO('mysql:host=localhost;dbname=your_db', 'username', 'password');
    $stmt = $pdo->prepare("INSERT INTO products (product_id, product_name, price, commission) VALUES (?, ?, ?, ?)");
    foreach ($products as $product) {
        $stmt->execute([
            $product['product_id'],
            $product['product_name'],
            $product['price'],
            $product['commission']
        ]);
    }
    */

    // Debug: Print the collected data
    echo "<pre>";
    print_r($products);
    echo "</pre>";
}
?>

Key Notes:

  • Fixed the typo in your original HTML: the "Name" input had name="productId[]" instead of productName[]
  • Added e.preventDefault() to the link clicks to prevent page jumps
  • If you want consecutive numbers after deleting groups, you can add logic to re-number all fields, but it's not necessary for PHP processing—unique, matching numbers per group are all that matter

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.11 09:29:05