Arrays in Forms

When I introduced my Cookie Toolbox I just listed the functions available in the toolbox without showing you how to use them. Then on my Using the Cookie Toolbox page, I tell you how you can use the functions in your pages.

One thing that wasn't covered in either of those pages was how you might go about creating an array in a form on your page and the easiest way to save the content of that form array to the cookie. The reason for this is that HTML doesn't really support defining form fields as arrays.

The best that you can do to create an array on a form is to give all of the fields that are part of the array related names. For the purpose of showing how to do this I will assume that we are going to give the array the name field and that we want the array to contain ten text fields ie field[0] through field[9]. Since HTML foesn't allow us to name the fields within an array we instead name them field0 through field9 which is as close as we can get to creating an array in HTML. This gives us code that looks like this (note that some parameters are omitted for clarity):

<input type="text" name="field0" />
<input type="text" name="field1" />
<input type="text" name="field2" />
<input type="text" name="field3" />
<input type="text" name="field4" />
<input type="text" name="field5" />
<input type="text" name="field6" />
<input type="text" name="field7" />
<input type="text" name="field8" />
<input type="text" name="field9" />

So now we have our array named in the form as best we can. The next step is to load that into a proper array and save it into a cookie. The code to do this is quite simple and we can even set it up so that it skips over any empty fields and loads all of the fields actually entered into as small an array as possible. Here's the javascript code to do it:

var cookieName = 'myname'; // give the cookie a name
var myarray = init_array();
j = 1;
for (var i = 0; i <
10; i++) {
  if (eval('form.
field'+i+ '.value') != "") {
    myarray[j] = eval('form.
field'+i+ '.value');
set_array(cookieName, myarray, expires);

You can of course easily change the number of entries from 10 to whatever you want and the name from field to whatever you want as well.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow