[英]Adding dynamic form elements 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'));
});
謝謝
您在數量div上拼錯了'recipe-quantity'類。
<div class="col-md-6 recipe-quantites">
變成
<div class="col-md-6 recipe-quantities">
目前,我可以在用戶點擊按鈕時添加我的一個表單元素,但第二個元素沒有與它一起添加。
使用動態添加的內容,您應該delegate
單擊delegate
給文檔(例如,包含對象的內容)。
$(document).on('click', '.recipe-ingredients #addNewIngredient', function () {
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.