Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Naming multiple select boxes through loop

Status
Not open for further replies.

FurryGorilla

Technical User
Apr 11, 2001
76
0
0
GB
Hi

I've set up a table on a page which has product information for each row in the table. Each table row has a select box which is named using
Code:
<select name=\"item_no_$i\"/>
where $i is a number that is incremented on each loop.

This then generates a series of select boxes named item_no_0, item_no_1, etc depending on how many products are in the table.

The problem I'm having is being able to access the value that is chosen in each select box. I understand that there will be variables named $item_no_0, $item_no_1 when the form is submitted but how can I access these using the $i variable?


Any help would be much appreciated.
Chris
 
You should inspect the $_POST variables.
Have a look what's posted with:
Code:
echo "<pre>";
print_r($_POST);
echo "</pre>";

You can loop through the posted values with a foreach() loop construct. Examine the key of the associative array, e.g. item_no_#
Code:
foreach($_POST as $key=>$value){
   echo $key." has value ". $value;
}

Hope this will give you an idea how to access the values.
 
Or better still, change the way you name the elements. Instead of a name of the form "item_no_$i", use "item[$i]". When the form is submitted, $_POST['item'] will itself be an array.

One "gotcha" naming elements this way -- JavaScript (and possibly VBScript) cannot access the elements when they're named this say. There is a workaround: create element tags of the form:

<select name="item[1]" id="item_1">

Then in client-side scripting (at least JavaScript), you can reference the elements if necessary using the id instead of the name.


Want the best answers? Ask the best questions!

TANSTAAFL!!
 
Thanks for both of those replies.

I've decided to go with the item[$i] method of naming and that seems to work fine. Thanks for the pointer regarding accessing the elements via javascript. Although I probably won't be using any client-side scripting it's always good to know :)

Thanks once again
Chris
 
An offtopic tip:

If you wish to have it SELECTED, please use
Code:
selected="selected"

I see a lot of people use only SELECTED.
Also all tags are preferred in lowercase, not UPPERCASE.

You might already know this.

Olav Alexander Mjelde
Admin & Webmaster
 
Yep, don't worry. I've been validating my xhtml as I go along so no uppercase tags or short selects.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top