用Javascript追加表单字段

用Javascript追加表单字段,javascript,jquery,html,forms,fieldset,Javascript,Jquery,Html,Forms,Fieldset,当使用Javascript动态添加包含在单个字段集中的其他表单字段时,我遇到了在第一个表单字段之后仍然应用关闭字段集标记的问题。这导致布局中断,我需要弄清楚如何解决这个问题 我试图将closing字段集标记移到附加字段的DIV之外,但是Firebug检查仍然显示它在第一项之后关闭 JAVASCRIPT <script type="text/javascript"> $(function() { var template = $('#inventoryItems .inven

当使用Javascript动态添加包含在单个字段集中的其他表单字段时,我遇到了在第一个表单字段之后仍然应用关闭字段集标记的问题。这导致布局中断,我需要弄清楚如何解决这个问题

我试图将closing字段集标记移到附加字段的DIV之外,但是Firebug检查仍然显示它在第一项之后关闭

JAVASCRIPT

<script type="text/javascript"> 
$(function()
{
    var template = $('#inventoryItems .inventory:first').clone(),
        inventoryCount = 1;

    var addInventory = function()
    {
        inventoryCount++;
        var inventory = template.clone().find(':input').each(function()
        {
            var newId = this.id.substring(0, this.id.length-1) + inventoryCount;
            $(this).prev().attr('for', newId); // update label for (assume prev sib is label)
            this.name = this.id = newId; // update id and name (assume the same)
        }).end() // back to .attendee
        .attr('id', 'inv' + inventoryCount) // update attendee id
        .appendTo('#inventoryItems'); // add to container
    };

    $('.btnAddInventory').click(addInventory); // attach event
});
</script>

$(函数()
{
var template=$('#inventoryItems.inventory:first').clone(),
存货计数=1;
var addInventory=函数()
{
inventoryCount++;
var inventory=template.clone().find(':input').each(function()
{
var newId=this.id.substring(0,this.id.length-1)+inventoryCount;
$(this.prev().attr('for',newId);//更新标签(假设prev-sib是标签)
this.name=this.id=newId;//更新id和name(假设相同)
}).end()//返回到.attendee
.attr('id','inv'+inventoryCount)//更新与会者id
.appendTo(“#inventoryItems”);//添加到容器
};
$('.btnAddInventory')。单击(addInventory);//附加事件
});
HTML


库存

您的HTML标记中有一个错误,一个额外的结束DIV标记,就在结束字段集标记之前。在
标记后移动它。清除
标记,您应该就没事了

当解析HTML并遇到closing DIV标记(对应于
#inventoryItems
)时,它会注意到您仍然有一个打开的字段集标记,因此它会为它插入close标记。之后,当遇到实际的结束字段集标记时,它被忽略,因为没有打开的字段集标记

原始错误在JS代码中。下一行将添加到DIV#inventoryItems而不是字段集

    .appendTo('#inventoryItems'); // add to container
尝试将其替换为:

    .appendTo('#inventoryItems > fieldset'); // add to fieldset

结束DIV是正确的,但正如我在原始帖子中提到的,我尝试将结束字段集移到它之外,因为在此之前我试图附加其他字段。我继续并将其向后移动,但它仍然与结束字段集设置在附加字段之前的情况基本相同。谢谢你!啊,太好了,这正是我们所缺少的。我对Javascript的缺乏经验再次引起了我的注意,但我非常感谢您帮助我解决这个问题!
    .appendTo('#inventoryItems > fieldset'); // add to fieldset