0

How do I create 2 HTML arrays from value pairs on form submit?

from <input type="text" name="val_a1" value="1">
to <input type="text" name="val_b1" value="2">

from <input type="text" name="val_b1" value="3">
to <input type="text" name="val_b1" value="4">

from <input type="text" name="val_c1" value="5">
to <input type="text" name="val_c1" value="6">

to look like

array[1,3,5] and array[2,4,6]

Do I need to five unique field names, like in my example or just keep val_a and val_b?

1
  • They must be unique or the server will not be able to distinguish one from another. This sort of stuff should be done serverside, not clientside. Commented Apr 22, 2011 at 23:37

3 Answers 3

2

Use brackets in the field names to have the input value return an array:

from <input type="text" name="from[0]" value="1">
to <input type="text" name="to[0]" value="2">

from <input type="text" name="from[1]" value="3">
to <input type="text" name="to[1]" value="4">

from <input type="text" name="from[2]" value="5">
to <input type="text" name="to[2]" value="6">

Note that the keys (0, 1, 2) are optional and could be anything you want (or none at all), but I used them so it would make more sense once you get the return values. You should receive from and to as an array when submitting the form now.

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

Comments

2

AFAIK you can have several query values with the same name. So it would then depend on what backend you are using to parse the querystring. Common practice is to name several fields that should be grouped together name[], and most backends will turn that into an array then. So try both methods out on your backend and check how they are treated!

Comments

1

if you just want an array you can do it like this

from <input type="text" name="from[]" value="1">
to <input type="text" name="to[]" value="2">

from <input type="text" name="from[]" value="3">
to <input type="text" name="to[]" value="4">

from <input type="text" name="from[]" value="5">
to <input type="text" name="to[]" value="6">

you don't need to number them they will be in order they are recieved

but you can go into nesting too see this post for more details

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.