Friday, January 25, 2019

javascript - Jquery button click() function is not working




I am trying to create dynamic form where user can add dynamic text-fields based on their requirement. Here is my jquery code ..



$(document).ready(function() {

$("#add").click(function() {
var intId = $("#buildyourform div").length +1;
var fieldWrapper = $("
");
var fName = $("");
var lname = $("");
var removeButton = $("");

var addButton = $("")
removeButton.click(function() {
$(this).parent().remove();

});
fieldWrapper.append(fName);
fieldWrapper.append(lname);
fieldWrapper.append(removeButton);
fieldWrapper.append(addButton);
$(this).remove();
$("#buildyourform").append(fieldWrapper);

});


});


and Html code is ...




Build your own form!










Check my JSFiddle also.



Whats wrong with me is when user click on "+" button first time then click function working and it adds two text-fields into my fieldset. But after that when i click on "+" button, its not triggering click function. May be id conflict. Please help.


Answer




You need to use the event delegation syntax of .on() here. Change:



$("#add").click(function() {


to



$("#buildyourform").on('click', '#add', function () {



jsFiddle example


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...