...

View Full Version : Save Select field input



cedtech23
03-24-2007, 08:08 AM
I am trying to use PHP to save entry on a user input in a form, so that if the user fails the form validation he/she
does not have to fill in the information they alread typed in the form the first time. I realize that I can use $_POST['key'] for input fields
but I am have trouble with saving select drop down menu input. I figured I would just create a blank option tag and place $_POST['key'] in between the brackets.
It works but I know there is a better more robust way to solve this issue. code below...



<label for="dept">Department: *</label>
<select name="dept" id="dept">
<option>$_POST['dept']</option>
<option>Accounting</option>
<option>Billing</option>
<option>Clinical</option>
<option>CR&D</option>
<option>Dental</option>
<option>Finance</option>
<option>FrontDesk</option>
<option>Laboratory</option>
<option>Medical Records</option>
<option>IS</option>
</select>



I did some research and I read about a technique where I would do something like the code below




<label for="dept">Department: *</label>
<select name="dept" id="dept">
<option></option>
<option <?php if($_POST['dept'] == 'Accounting'){ echo 'selected="selected"'; } ?> >Accounting</option>
<option <?php if($_POST['dept'] == 'Billing'){ echo 'selected="selected"'; } ?>>Billing</option>
<option>Clinical</option>
<option>CR&D</option>
<option>Dental</option>
<option>Finance</option>
<option>FrontDesk</option>
<option>Laboratory</option>
<option>Medical Records</option>
<option>IS</option>
</select>


as you can see this can lead to a lot of extra lines of code. Does anyone know of a better more robust way to save the user input
in a form? maybe using an array

cedtech23
03-24-2007, 09:32 AM
OK, I took the approach of using an array; but I am missing something in the code I am getting an extra > and I can see the php when I view the source.
any ideas thanks




<label for="dept">Department: *</label>
<select name="dept" id="dept">
<?php
$dept = array('Billing', 'Clinical', 'CR&D', 'Dental', 'Finance', 'FrontDesk', 'Laboratory', 'Medical Records', 'IS');

foreach($dept as $name) {
echo '<option <?php if($_POST[\'dept\'] == '.$name.'){echo \'selected="selected"\';} ?>>'.$name.'</option>';
}
?>
</select>

cedtech23
03-24-2007, 02:19 PM
Thanks a little sleep and I got it :thumbsup:



<label for="dept">Department: *</label>
<select name="dept" id="dept">
<?php
$dept = array('Billing', 'Clinical', 'CR&D', 'Dental', 'Finance', 'FrontDesk', 'Laboratory', 'Medical Records', 'IS');

foreach($dept as $name) {
$selected = '';
if ($_POST['dept'] == $name){
$selected = ' selected';
}
echo '<option value="'.$name.'"'.$selected.">{$name}</option>\n";
}
?>
</select>



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum