Mateusz Bartkowski
Mateusz Bartkowski

Reputation: 729

Handling dynamic input groups

I am creating a form where a part of it would be cloned using javascript. The input name is of type input[ID][date], input[ID][type] etc. where the ID is the group of inputs. Those will be relationship IDs decided after the form submission.

I am currently having a placeholder for ID which gets replaced on cloning by the current element count.

Problem

When someone adds 3 elements ([0],[1],[2]) and removes the first one, the next ID of the element will be 2, same as the third element, overtwriting its inputs. I can't use input[][date] because it will create separate array for each input.

Question

What is the best way to approach dynamic input arrays? Should I keep the ID as a variable and increment it every time so it's unique even after removing an element? Would random temporary ID work? (I guess it could repeat that way)

Upvotes: 0

Views: 69

Answers (1)

Asking Questions
Asking Questions

Reputation: 404

I did something like this a while ago, here is how.

I stored each element name/id in an array ["inputname1", "inputname2"].

Then when ever a user would add a new element I would re iterate my array ["inputname1", "inputname2", "inputname3"] and replace each name id with the new id number based on how many inputs I have iterated over.

If an input got deleted the array would shift, no worries about same input id number.

More efficient than the original(you dont need to refresh each input remove button or their ids) Example

Original Example

Sorry if I did not explain well enough.

Upvotes: 1

Related Questions