2015-12-16 198 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 –