繁体   English   中英

添加动态表单元素jQuery

[英]Adding dynamic form elements jQuery

我试图使用jQuery将动态表单元素添加到我的页面。 目前,我可以在用户点击按钮时添加我的一个表单元素,但第二个元素没有与它一起添加。

我通过在单击按钮时将一些html附加到具有特定类的div来执行此操作。

我创建了一个JSfiddle。 正如您所看到的,“成分”部分正在运行,但数量不是。

https://jsfiddle.net/fe0t​​3by2/

$('.recipe-ingredients #addNewIngredient').on('click', function () {
        var i = $('.recipe-ingredients .ingredient').size() + 1;
        $('<div class="form-group ingredient"><label class="control-label" for="searchinput">Ingredients</label><div><input id="ingredient_' + i + '" name="ingredients[]" type="text" placeholder="Ingredients" class="form-control input-md"></div></div><a href="javascript:void(0)" class="pure-button pure-u-1-6 pure-button-primary" id="addNewIngredient">Add Ingredient</a></div>').appendTo($('.recipe-ingredients .ingredients'));
        $('<div class="form-group"><label class="control-label" for="buttondropdown">Quantity</label><div class="input-group"><input id="quantity_' + i + '" name="quantity[]" class="form-control" placeholder="Quantity" type="text"><div class="input-group-btn"><button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Measure<span class="caret"></span></button><ul class="dropdown pull-right"><li><a href="#">Grams</a></li><li><a href="#">Ounces</a></li><li><a href="#">Option three</a></li></ul></div></div>').appendTo($('.recipe-quantities .quantities'));
});

谢谢

您在数量div上拼错了'recipe-quantity'类。

<div class="col-md-6 recipe-quantites">

变成

<div class="col-md-6 recipe-quantities">

目前,我可以在用户点击按钮时添加我的一个表单元素,但第二个元素没有与它一起添加。

使用动态添加的内容,您应该delegate单击delegate给文档(例如,包含对象的内容)。

jQuery文档.on()

$(document).on('click', '.recipe-ingredients #addNewIngredient', function () {

JSFiddle演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM