Search code examples
javascriptjqueryflatpickr

Dynamic form field adding clears the input for all fields


I have created a form that you can dynamically add and remove fields to. I am so close to getting it working, but for some reason I can fill in the first fields, add a new field and the first field data remains. Then when I add a second field, fill it in and add another, it will clear all existing data.

I can tell that the flatpickr calendar is always on the first field, but then when I add subsequent fields, the flatpickr calendar only applies to the last field and won't actually show for any in between. I really need some help as I've spent so long trying to figure it out :(

I believe this is an issue with my JS and how it gets the last element, not how it calls the flatpickr library.

Here is all my code in a JSFiddle: https://jsfiddle.net/danboy4/w9s9ayep/

Thanks!


Solution

  • You were right with your assumption that the error was located at how it gets the last element. You had the following code:

    var html = $(".copy-fields").html();
    $(".after-add-more").after(html);
    
    var lastInput = $(".control-group").closest(".start").prevObject 
    var lastInput2 = lastInput[lastInput.length-2].getElementsByClassName("start")[0];
    

    This would add the new copied fields directly after the first input box but when getting the element from the array you wanted to use flatpickr on you'd use lastInput.length-2. This index would always be the index of the LAST visible box. The problem was that the box you newly added was not the LAST visible box but actually the second one (because it is directly added after the first input box). Therefore it would overwrite the previous values.

    So if you just change var lastInput2 = lastInput[lastInput.length-2].getElementsByClassName("start")[0]; to var lastInput2 = lastInput[1].getElementsByClassName("start")[0]; it'll work as it's supposed to be.

    Alternatively you could leave the var lastInput2 = lastInput[lastInput.length-2].getElementsByClassName("start")[0]; as it is and instead change where the new element is placed. To always place it at end you could do something like this $("#button").before(html);

    Hope I could help you.