Select list validation

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
therat
Forum Commoner
Posts: 62
Joined: Wed Oct 01, 2003 2:44 pm
Location: London

Select list validation

Post by therat »

When validating a select list how can I default the list to what the user has chosen if other parts of the form have errors.
With a text field I have the following that shows what the user entered if other parts of the form have errors. I need to do the same thing for the select list
Text Box

Code: Select all

<input type=&quote;text&quote; name=&quote;subs_title&quote; size=&quote;32&quote; value=&quote;<?php echo $subs_title; ?>&quote; class=&quote;mainoption&quote;>
Select List

Code: Select all

<select name=&quote;subs_res&quote; class=&quote;mainoption&quote;>
<option selected=&quote;selected&quote;>Select....</option>
<option>640*480</option>
<option>800*600</option>
<option>1024*768</option>
<option>1152*864</option>
<option>1280*1024</option>
<option>1600*1200</option>
<option >Other</option></select>
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

I like to store my list options in an array and then array_unique with the post value in the list.

Code: Select all

$options = array($_POST['selected'],'640*480','800*600','1024*768','1152*864',',1280*1024','1600*1200','Other');
$options = array_unique($options);

echo '<select name="subs_res" class="mainoption">
<option selected="selected">Select....</option>';

foreach ($options as $option)
{

echo '<option>'.$option.'</option>';

}

echo '</select>';
therat
Forum Commoner
Posts: 62
Joined: Wed Oct 01, 2003 2:44 pm
Location: London

Post by therat »

Thanks, I'll try that.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

o.O

Code: Select all

$options = array('Select...' =&gt; 0, '640*480' =&gt; 1, '800*600' =&gt; 2, ... );

$out = '&lt;select name=&quote;subs_res&quote; class=&quote;mainoption&quote;&gt;' . &quote;\n&quote;;

$selection = (isset($_POST&#1111;'subs_res']) ? intval($_POST&#1111;'subs_res']) : 0);

foreach($options as $mark =&gt; $value)
{
  $out .= '&lt;option value=&quote;' . $value . '&quote;' . ($select === $value ? ' selected=&quote;selected&quote;' : '') . '&gt;' . $mark . '&lt;/option&gt;' . &quote;\n&quote;;
}

$out .= '&lt;/select&gt;';

echo $out;
Post Reply