I'm trying to append another form-group.
The button at the form-group added is not working.
Can anyone tell me why?
<div class="form-group">
<input type="text"/>
<button class="add">Add</button>
</div>
JS
$('.add').click(function(){
$('.form-group').append(
'<input type="text"/>'+
'<button class="add">Add</button>'
);
})
You need to use event delegation via .on() for dynamically added elements:
$('.form-group').on('click', '.add', function() {
$('.form-group').append(
'<input type="text"/>' +
'<button class="add">Add</button>'
);
})
jsFiddle example
Related
I have the following HTML :
<button type="button" id="Button">Go</button>
<div id="validation"></div>
I'm trying to add event handlers to dynamically generated elements in the following way :
Click button -> Generate element X inside div #validation -> Attach event handler to element X
$(document).ready(function(){
ID = 1;
$("#Button").click(function(){
/*generate new div inside div #validation with id #validationID
1st one would be #validation1
it contains a form with name accepterID and a button with name refuserID
1st ones would be accepter1 and refuser1*/
var newline = `
<div id="validation${ID}">
<form name="accepter${ID}">
<input type="hidden" name="name" value="phoegasus">
<button type="submit" value="valider">
</form>
<button name="refuser${ID}">refuser</button>
</div>
`
$("#validation").append(newline);
/*attach event handlers to the generated elements
1st iteration would attach handlers to accepter1 and refuser1 */
$("#validation").on('submit',"form[name^='accepter"+ID+"']",function(e){
$("#validation" + ID).remove();
//remove div validationID after submitting form
});
$("#validation").on('click',"button[name^='refuser"+ID+"']",function(){
$("#validation" + ID).remove();
//remove div validationID
});
ID++;
});
});
When I submit the form or I click the generated button I want to remove the div that contains them. If I press the button refuser1, it should delete the div #validation1.
When the elements are generated the handlers aren't attached to them.
The code doesn't work when it's executed during the onclick event but when I execute it in the navigator console it works.
I tried using DOMSubtreeModified on the div with id #validation, but it didn't work.
you can manage it by using a class (or another element) in second argument of your on function.
For that, DO NOT declare your event listeners inside your add event.
This is a full working example :
$("#validation").on('submit',"form.validation-form",function(e){
e.preventDefault();
console.log('form', $(this).attr('data-id'), ' submitted');
});
$("#validation").on('click',"button.validation-refuser",function(){
console.log('clicked on refuser for form ', $(this).attr('data-value'));
//code
});
var ID = 1;
$('#my-adder').on('click', function () {
$('#validation').append('<form name="accepter'+ID+'" class="validation-form" data-id="'+ID+'"><input type="text" placeholder="my text field" /><button class="validation-refuser" name="refuser'+ID+'" data-value="'+ID+'">Refuser button</button><button type="submit">SUBMIT</button></form>');
ID++;
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="validation">
<form name="accepter0" class="validation-form" data-id="0">
<input type="text" placeholder="my text field" />
<button type="button" class="validation-refuser" name="refuser0" data-value="0">Refuser button</button>
<button type="submit">SUBMIT</button>
</form>
</div>
<button id="my-adder">ADD A FORM</button>
Hope it helps
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.
I have the following markup:
<div id="section">
<input type="text" id="myInput">
</div>
On click of a button, I'm cloning and inserting a copy of this markup with unique IDs using this script:
var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" + ($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);
My resulting markup:
<div id="section">
<input type="text" id="myInput">
</div>
<div id="section2">
<input type="text" id="myInput2">
</div>
My question: is it possible to manipulate this new markup with jQuery? I assume since it has loaded dynamically after a click it's not part of the initial DOM and jQuery doesn't recognize it? I'm having trouble getting a click event to register on #myInput2. Thanks for any insight.
Add classes to your markup:
<div id="section" class="section">
<input type="text" id="myInput" class="section-input">
</div>
Simplify your code
var $newSection = $('#section').clone();
var $sections = $('.section');
var index = $sections.length +1;
$newSection.attr('id', 'section' + index);
$newSection.find('input').attr('id', 'myInput' + index);
$sections.last().after($newSection);
Make sure click handlers are added to existing and new elements
$(document).on('click', '.section-input', function(){
... your code
})
if you wrap them in a container, you can delegate that container keep track of the buttons. For example, if you have:
<div id="container">
<div id="section">
<input type="text" id="myInput">
</div>
<div id="section2">
<input type="text" id="myInput2">
</div>
</div>
you can delegate the task to the container like this:
$("#container").on("click","input",function(){
var newSection = $("#section").clone();
$(newSection).attr('id', "section" + ($("div[id^=section").length + 1));
$(newSection).find("input").attr('id', "myInput" +
($("input[id^=myInput").length + 1));
$("div[id^=section").last().after(newSection);
}
This way you can manipulate them if not defined while binding
EDIT: Updated from .delegate() to .on()
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
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();
});