【发布时间】:2015-12-16 09:58:39
【问题描述】:
我正在尝试使用 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'));
});
谢谢
【问题讨论】:
-
还有为什么
Add Ingredient按钮会重复 -
ID应该是唯一的,您可以创建多个。请改用class -
你有一个错字 -
recipe-quantities(js) 与recipe-quantites(类名) - 在ties中缺少i- jsfiddle.net/arunpjohny/dqvds66s/1
标签: javascript jquery html css