添加动态表单元素jQuery

时间:2015-12-16 09:58:40

标签: javascript jquery html css

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

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

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

https://jsfiddle.net/fe0t3by2/

$('.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'));
});

谢谢

2 个答案:

答案 0 :(得分:1)

你拼错了食谱量&#39;你的数量div上课。

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

更改为

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

答案 1 :(得分:0)

  

目前,我可以在用户点击按钮时添加其中一个表单元素,但第二个元素不会随之添加。

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

jQuery documentation .on()

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

JSFiddle demo

相关问题