简体   繁体   中英

Adding dynamic form elements jQuery

I am attempting to use jQuery to add the dynamic form elements to my page. At the moment I can get one of my form elements to be added when the user clicks the button but the second element isn't being added alongside it.

I do this by appending some html to divs with a specific class when a button is clicked.

I have created a JSfiddle. As you can see the 'ingredient' part is working, however the quantities is not.

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

Thank you

You have misspelled the 'recipe-quantities' class on your quantities div.

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

changed to

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

At the moment I can get one of my form elements to be added when the user clicks the button but the second element isn't being added alongside it.

With dynamically added content you should delegate the click to the document for example (something where the object is contained in).

jQuery documentation .on()

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

JSFiddle demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM