Andrew Liu
Andrew Liu

Reputation: 2548

How to append additional sets of fields to html form

Example: let's say we have a form with 3 fields: pc, part_id, part_details. Sometimes you will want to add additional parts to database when adding pc, so part_id and part_details should be duplicated(part_id and part_details should be corresponding). What I want is the best way to append this two fields to the form?

I know if you just want to duplicate one field you can name the field like this:

<input type="text" name="part_id[]">

Then we can easily get the post data as array. But now we are duplicating more than one field, if we use the approach above at the post end the two/multiple arrays will not be relevant. The approach described here seems to be a good one http://www.quirksmode.org/dom/domform.html, but the fact that names are changing all the time makes it complicated to use the post data as well.

There is another possible approach described here Multiple Forms With Input Fields With The Same Name Attribute? Good Or Bad? . It gives an idea to duplicate the entire form. I am not sure if I understand it correctly, but when I try putting two identical forms in the same page and submit one of them, only data from this form will be submitted, the other one will be ignored. Also it is not suitable for my scenario as not all the fields should be duplicated.

So what is the best way to accomplish this duplicating job?

Upvotes: 0

Views: 248

Answers (2)

sahbeewah
sahbeewah

Reputation: 2690

In the link you gave, they didn't duplicate the form, just the elements inside the form which is fine. If all you are adding is multiple parts to a single PC then there shouldn't be a problem. The parts will be linked via array indices (you can rely on the ordering).

The first instance of part_id[] will correspond to the first instance of part_details[]. This should be distinguishable in your server-side language. In PHP for instance, part_details[2] will correspond to part_id[2] etc.

Upvotes: 1

Stefano Dalpiaz
Stefano Dalpiaz

Reputation: 1673

You can use another level of indexing:

<input type="text" name="pc" />

<!-- First part -->
<input type="text" name="parts[0][part_id]" />
<input type="text" name="parts[0][part_details]" />

<!-- Duplicate part -->
<input type="text" name="parts[1][part_id]" />
<input type="text" name="parts[1][part_details]" />

<!-- Another duplicate part -->
<input type="text" name="parts[2][part_id]" />
<input type="text" name="parts[2][part_details]" />

The fields for each part (id and details) can be easily generated using jQuery.

Upvotes: 1

Related Questions