2015-12-16 199 views
3

我正在尝试使用jQuery将动态表单元素添加到我的页面。目前,我可以在用户单击按钮时添加一个表单元素,但第二个元素不会被添加到旁边。添加动态表单元素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

此外为什么是'添加Ingredient'按钮重复 –

+0

'ID'的应该是独一无二的,你创建多个。用'class'代替 –

+2

你有一个拼写错误 - 配方量(js)与'recipe-quantites'(类名) - 在'ties'中缺少'i' - https://jsfiddle.net/arunpjohny/dqvds66s/1/ –

回答

1

您有拼写错误您数量DIV的 '偏方量' 级。

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

改为

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

此刻,我可以得到,当用户点击该按钮后的第二个元素不被它的旁边添加添加我的表单元素之一。

随着动态添加内容你应该delegate的点击文档,例如(一些地方的对象包含在)。

jQuery documentation .on()

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

JSFiddle demo

+0

这是正确的,但我真的怀疑用户真的想每次添加新按钮。感觉很奇怪 – Enjoyted

+0

完全同意,它根本不是用户友好的。 @Enjoyted –