Mateusz Bartkowski Mateusz Bartkowski - 1 year ago 80
PHP Question

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

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.


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
because it will create separate array for each input.


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)

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download