pocockn
pocockn

Reputation: 2073

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

Upvotes: 3

Views: 305

Answers (2)

Daan
Daan

Reputation: 2799

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

Upvotes: 0

LunchBaron
LunchBaron

Reputation: 160

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">

Upvotes: 1

Related Questions