Adding dynamic form elements jQuery - javascript

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>Add Ingredient</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>Grams</li><li>Ounces</li><li>Option three</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

Related

Prevent reload page with code added afterwards and after clicking a button

first of all I'm trying to create a form where is needed to duplicate some blocks of fields and fields as the user want.
So I have a page where there is a button that after clicking on it duplicates a certain block. The first button works fine!, it duplicates a block without reloading the page when is clicked.
But in that block there are some input fields that I need to duplicate as well.
So when the block is duplicated a new button is added to duplicate fields inside that block.
The problem is that when I click on the second button it reloads the page, instead of just duplicate an input field.
To do this I'm using jquery, code to duplicate the block, this is the code to add the block, that is working fine:
$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
event.preventDefault();
});
code to duplicate the field (here is where the page reloads):
$('#we2_add_test').click(function(e) {
event.preventDefault();
$(".we2_test-input").append("<input type=\"text\" placeholder=\"Your Test\" class=\"form-control\" name=\"we3_test\" id=\"we3_test\">");
return false;
});
I already tried this, but it didn't work
1.id="we2_test" need to be class="we2_test" and id=we2_add_test need to be class="we2_add_test",because multiple same id for different HTML element is wrong when you are going to deal them with jQuery
2.Use event delegation:-
Now both code need to be:-
$('#add-block').click(function(e) {
e.preventDefault();
var html_to_add = '<input type="text" placeholder="Your Test we2_test" class="form-control" name="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test we2_add_test">+</button>';
$(".block-input").append(html_to_add);
});
$(document).on('click','.we2_add_test',function(e) {
e.preventDefault();
$(".we2_test-input").append("<input type='text' placeholder='Your Test' class='form-control we3_test' name='we3_test'>");
});
The first function has event as the function argument, but later on you try to use e.preventDefault(). That doesn't match.
Maybe
$('#add-block').click(function(e) {
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test">';
html_to_add += '<div class="we2_test-input col-md-12 no-pad"></div>';
html_to_add += '<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
e.preventDefault();
});
will work? Difficult to say without the complete code though ...
Below is a somehow working version...
This is a little working snippet where I took care of the identity problem and the event delegation as mentioned/solved by #Alive to Die:
$(function(){
$('#add-block').click(function(e) {
var i=$('[name=we2_test]',".block-input").length;
var html_to_add = '<input type="text" placeholder="Your Test" class="form-control" name="we2_test" id="we2_test'+i+'">'
+'<div class="we2_test-input col-md-12 no-pad"></div>'
+'<button class="btn btn-default btn-add-test" id="we2_add_test">+</button>';
$(".block-input").append(html_to_add);
e.stopPropagation();
return false;
});
$('.block-input')
.on('click','#we2_add_test',function(e) {
e.preventDefault();
var j=$('[name=we3_test]',".we2_test-input").length;
$(this).prev().append('<input type="text" placeholder="Your Test" class="form-control" name="we3_test" id="we3_test'+j+'">');
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
add block
<div class="block-input"></div>
Edit:
I replaced $(".we2_test-input").append(...) by $(this).prev().append(...) to ensure that only the div before the button gets added to.

how to generate the id of a div dynamically using javascript

I have a (+) sign and a (-) sign. If the user clicks on the + sign than whatever their in the row will automatically get generated the same with new id.
Now when user click on + sign than div id and text box under it will get changed.
Code below for div as follows:
<div class="row" id="Div0">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control" id="txtLastName0" placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
Now when user clicks on + sign the new row with text box with new id txtLastName1 will get generated.
Now on click of + sign how do i get new id of textbox and a div with new row.
Div1 and textbox1 will get generated
Basically what you should do is, keep the markup you want to generate as a template in your DOM and when user clicks the "Add" button, clone this markup and append to the DOM (to a container div). then update the Id's of the input and divs as needed.
A simply sample would be like
<div class="row" id="template" style="display: none;">
<div class="col-md-3">
<div class="form-group">
<label for="name">Last Name</label>
<input type="text" class="form-control lname" id="txtLastName"
placeholder="Enter name" required="required" />
</div>
</div>
<div class="col-md-9"></div>
</div>
<button id="btnAdd">+</button>
<div id="container"></div>
Now wire up a click event handler to the Add/+ button. You may use the jQuery clone() method.
$(function () {
$("#btnAdd").click(function(e) {
e.preventDefault();
var childCount = $("#container").children().length;
var c = $("#template").clone().show();
c.attr("id", "Div" + childCount );
c.find(".lname").attr('id', 'txtLastName' + childCount);
$("#container").append(c);
});
});
For deleting, you can add a event handler on the delete button and remove the specific div from dom. jQuery remove() method will do it. Use closest() and find as needed to get the correct div to remove.
Here is a working simple jsbin sample for your reference

How to remove input group in bootstrap?

This is what I have right now. I'm trying to add fields to the form dynamically using jQuery add() and append() method. But I want to remove the particular added field when the remove button is clicked.
<div class="col-md-12">
<h3>Added Description Fields</h3>
<div class="col-md-12" id="descFields">
</div>
</div>
JS
$(document).ready(function() {
console.log(descFields);
$('#addDesc').click(function(e) {
var descFields = $('#descFields');
var descLabel = $('#descLabel').val();
var large = '<div class="form-group" id="descField"><div class="input-group"><input type="text" class="form-control" placeholder="Enter Value For ' + descLabel + '" /><span class="input-group-btn"><button class="btn btn-danger" id="removeDesc" type="button">Remove</button></span></div>';
descFields.add(large).appendTo(descFields);
e.preventDefault();
});
$('#removeDesc').click(function(e) {
$(this).remove();
});
});
When the user click on the #removeDesc button , the the field that is added should be removed. I cannot figure out how to achieve this.
There are many ways of doing this, but the simpler for your problem is this one:
$(document).ready(function() {
console.log(descFields);
$('#addDesc').click(function(e) {
var descFields = $('#descFields');
var descLabel = $('#descLabel').val();
var large = '<div class="form-group" id="descField"><div class="input-group"><input type="text" class="form-control" placeholder="Enter Value For ' + descLabel + '" /><span class="input-group-btn"><button class="btn btn-danger" id="removeDesc" type="button">Remove</button></span></div>';
descFields.add(large).appendTo(descFields);
e.preventDefault();
});
$('#descFields').on('click', '#removeDesc', function(e) {
$(this).parents('.form-group').remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="descLabel"/>
<button id="addDesc">Add Desc</button>
<div class="col-md-12">
<h3>Added Description Fields</h3>
<div class="col-md-12" id="descFields">
</div>
</div>
Your problem is in the callback to delete the rows. When the document has finished loading you are trying to attach a click event to an object #removeDesc that is still not present in the DOM because it's created on the fly when the user clicks the #addDesc.
That's why you should use:
$('#descFields').on('click', '#removeDesc', function(e) {
$(this).parents('.form-group').remove();
});
As #vijayP suggested before you can use the on() to attach an event handler to the container where you'll be adding the object that is still not present in the DOM. Then you pass in the query selector as the second parameter to filter in execution time which of its children will trigger the event and execute the callback.
My additional trick is that I'm using .parents('.form-group') to select the div containing the group and remove all of the fields that were added instead of removing only the button.
Happy coding!
Add click event for remove button like follows:
$(document).on("click","#removeDesc",function(e) {
$(this).remove();
});

jQuery append does not consider CSS of the div

I tried to add an item to a main div when clicking in the button add item, this should (every time) add a new line ( a text input), to the main content. This works fine.
The problem is that the text input has some css (some width and height...), which is not loading when adding it with jQuery, so the add works fine but it shows a "normal" unstyled text input, not mine (witch is styled).
here my HTML.
<fieldset class="lodging-info-fieldset" id="all_field">
<legend>Gage sur &eacutequipement projet</legend>
<div class="panel-heading score_pannel">
<ul class="panel-heading-fieldset">
<li>D&eacutesignation</li>
<li>Valeur</li>
</ul>
</div>
<div class="form-group" id="extended">
<div class="col50 left ">
<input type="text" class="form-control" id="designation"
placeholder="">
</div>
<div class="col50 left ">
<input type="text" class="form-control" id="valeur"
placeholder="">
</div>
</div>
<div class="form-group">
<div class="add_plus">
<a id="add_pluss" class='add_plus'>add item </a>
</div>
</div>
</fieldset>
and my jQuery append function:
addLigne : function(event) {
$("#all_field")
.append(
'<div class="form-group">'
+ '<div class="col50 left">'
+ '<input type="text" class="form-control" id="designation">'
+ '</div></div>');
},
Any ideas?
Thanks a lot for your help!
I don't know how you are styling it (we need to view your CSS code), but you are duplicating and N-plicating the same ID element, and is not good practice because you can't access to this element with a correct code (maybe with cruft but is not clean and properly).
Please, think about it and try to change ids with a unique string, like numbers for example.
addLigne : function(event) {
$("#all_field")
.append(
'<div class="form-group">'
+ '<div class="col50 left">'
+ '<input type="text" class="form-control" id="designation_'+ ($('input[id^="designation_"]).length + 1) +'">'
+ '</div></div>');
},
When you show us your CSS we can help you with your real problem.
Good luck

How to hide, when page starts, html element generated automatically with jQuery

When page starts, jQuery produce a form that I want it to be hidden. Because I want to show it when I click on a button.
With these instructions I create the form:
$("#cards").append('<li id="card" class="feed-element animated fadeInRight" style="color: grey" data-user="' + key + '">\n\
<button id="previewCard" type="button" value = "' + key + '" class="btn btn-primary btn-sm btn-block btn-xs">' + preview + '</li>\n\
<form id="cardFormDetail" class="animated fadeInRight">\n\
<div class="form-group">\n\
<input id="customerCardDate" class="form-control" type="text">\n\
</div>\n\
<div class="form-group">\n\
<input id="customerCardScope" class="form-control" type="text">\n\
</div>\n\
<div class="form-group">\n\
<textarea id="customerCardText" class="form-control" rows="5"></textarea>\n\
</div>\n\
</form>\n\
<button id="modifiedCard" type="button" value = "' + key + '" class="btn btn-primary btn-xs pull-left">Modified</button>\n\
<button id="deleteRequestCard" type="button" value = "' + key + '" class="btn btn-primary btn-xs pull-right">Delete</button>\n\
<br><hr style="border-color: #c80b00;">');
When page starts cardFormDetail form is visible. How can I make it not visible?
I tried with $("#cardFormDetail").hide() but it doesn't work. And the reason is because it is a dynamic element, right?
Since you want to hide it on load, pls use CSS as opposed to jQuery unless there is a reason to justify why you want to do it so.
#cardFormDetail { display: none; }
put your code which hides the form after the code where it appends the element to the.
Another things is you are appending an element with the same id 'cards' to an existing element which has the same id.
It doesn't matter if your element is dynamically added, you should always be able to hide it using jquery.
Can you post the whole code?

Categories