1

so I have this basic bootstrap form and I have a button called add another location which will dynamically create another 4 inputs to add more location. This is achieved via jquery and jquery UI. So I made 3 copies of this form and put them in a list because eventually, they are going to come from a server and loop the form depends on however many sets of information available. The problem I am having is that, only my first add another location button works and it's creating additional inputs on the second and third one as well. I can give different id/class to the buttons where the new form goes but that wouldn't do me any good since more or fewer forms can be displayed via the server. My question is how can each button act independently without giving different id/class to it. so if I click add another location button on the second set of form, it only creates additional inputs on the second set not first or 3rd, same for 1st set and 3rd set.

this is the jquery code that clones and appends the new inputs

    $("#pm-do-clone1").click(function () {

    $(".pm-clone-this3 .pm-clone4").clone().appendTo(".pm-clone-here1");
});

here's my jsfiddle : https://jsfiddle.net/jaisilchacko/yqvd4Lvv/4/ ps: the fiddle the first add location is not creating new inputs, but it works on my local.Probably an external resource issue

1
  • You are dynamically adding new elements to the DOM. Change this line $("#pm-do-clone1").click(function () { to this $(document).on('click', '#pm-do-clone1', function () {. This will allow you to apply a click event to elements added both before AND after the DOM has been loaded. Commented Oct 6, 2017 at 22:50

1 Answer 1

1

alright, as I understand You gotta grab the clicked button by referancing it with;

 $("#pm-do-clone1").click(function () {
 $(this).//rest of the code

and at the rest of the code as we captured the clicked one, we now have to find its parent where we gonna add the new inputs. For example,

var y = document.createElement('input');
var x =$(this).parents('.form');
$(x).append(y);

Edit: Btw, you are clicking an ID, ID is not the best model to catch one from multiple elemets because it sometimes make mistakes, use class instead.

Edit2: Check this snippet too. I belive this will help you. View DEMO

Edit3: Why do you wrapping each inputs into divs? It seems not necessary no create too much elements as you could achive the same result with only inputs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.