views:

336

answers:

1

I'd like to replace a multiple select box like:

<select multiple="multiple" name="options">  
<option value="option1">option1</option>  
<option value="option2">option2</option>  
...  
</select>

with an arbitrary number of simple select boxes:

<select name="options1">  
<option value="option1">option1</option>  
<option value="option2">option2</option>  
...  
</select>  

<select name="options2">  
<option value="option1">option1</option>  
<option value="option2">option2</option>  
...  
</select>

Is there any way to send and retrieve via POST an array of select boxes or should I try to access every select box named options(number) until it fails? Seems a bit dirty.

I should be able to submit an action to "delete this select box" or "create new select box" so I need some way to distinguish the select boxes.

+1  A: 

Just give the select elements the same name.

HTML forms have no concept of "an array". Every form handling library that handles arrays of input data generates them from a name having multiple values:

foo=bar&foo=baz&aDifferentField=fizzbuzz

This is what a multiple select (named foo) with two values selected will generate (when there is 'aDifferentField' in the form too).

Sometimes there are provisos involved.

Perl's CGI.pm needs the request for the data to be in list context:

my @foos = $cgi->param('foo');

PHP requires the name to end with the characters '[]'

name="foo[]"
foo[]=bar&foo[]=baz&aDifferentField=fizzbuzz

… but it all comes down to the names being the same (although the ids must still be different).

As for the deletion:

<label for="foo5">Group 5</label>
<select name="foo" id="foo5">
    <option value="delete_foo5">Delete this group</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>
David Dorward