动态文本框没有被删除

Dynamic textboxes are not removing

本文关键字:删除 文本 动态      更新时间:2023-09-26

我通过jquery添加文本框,对于一个文本框,它是完美地删除,但当我添加两个文本框,然后它现在都删除。

这是jquery

<script>
$(document).ready(function($){
    $('.product-form .add-product').click(function(){
        var n = $('.text-product').length + 1;
        var product_html = $('<p class="text-product"><label for="product' + n + '">Name <span class="product-number">' + n + '</span></label> <input required type="text" name="productnames[]" value="" id="product' + n + '" /> <label for="productprice' + n + '">Price <span class="product-number">' + n + '</span></label> <input required type="text" name="productprices[]" value="" id="productprice' + n + '" /><a href="#" class="remove-product">Remove</a></p>');
        product_html.hide();
        $('.product-form p.text-product:last').after(product_html);
        product_html.fadeIn('slow');
        return false;
    });
    $('.product-form').on('click', '.remove-category', function(){
        $(this).parent().fadeOut("slow", function() {
            $(this).remove();
            $('.product-number').each(function(index){
                $(this).text( index + 1 );
            });
        });
        return false;
    });
});
</script>

这是我的html

<div>
        <form>
            <div class="product-form">
                <p class="text-product">
                    <label for="product1">Name <span class="product-number">1</span></label>
                    <input required type="text" name="productnames[]" value="" id="product1" />
                    <label for="product1">Price <span class="product-number">1</span></label>
                    <input required type="text" name="productprices[]" value="" id="product1" />
                    <div>
                        <a class="add-product" href="#">Add More</a>
                    </div>
                </p>
            </div>
            <div>
                <input type="submit" name="submitDetails" value="Finish"/>
            </div>
        </form>
    </div>

如果只添加一个文本框,例如productnames,那么它的删除功能可以工作但当我同时添加productnames和productprices时,文本框删除功能不会同时删除

您的代码应该是$('.product-form').on('click', '.remove-product', function()而不是'click', '.remove-category'。另外,不要将Add Morediv元素放在段落元素中。编号也有一点中断,但您可以找出