Forum Moderators: coopster

Message Too Old, No Replies

How to choose selected dropdown option by variable

         

jbearnolimits

2:50 am on Oct 25, 2022 (gmt 0)

Top Contributors Of The Month



I know how to make the basic html form and use selected to have the dropdown show a certain option by default. But what I don't know is how do you choose the selected option based on the value stored in the database? For example, I have a dropdown like the following:

<select id="Type" name="Type" value="<?php echo "$Type";?>">
<option value="Agents/Offices">Agents/Offices</option>
<option value="Appraisers">Appraisers</option>
<option value="Cleaning Service">Cleaning Service</option>
<option value="Client">Client</option>
<option value="Contractor">Contractor</option>
<option value="Credit Repair">Credit Repair</option>
<option value="Escrow">Escrow</option>
<option value="Estate Sales">Estate Sales</option>
<option value="Expireds">Expireds</option>
<option value="FSBO">FSBO</option>
<option value="Inspectors">Inspectors</option>
<option value="Investors">Investors</option>
<option value="Movers">Movers</option>
<option value="Notice Of Default">Notice Of Default</option>
<option value="Personal">Personal</option>
<option value="Prospects">Prospects</option>
<option value="Staging">Staging</option>
<option value="Termite">Termite</option>
<option value="Title">Title</option>
<option value="Transaction Coordinator">Transaction Coordinator</option>
</select>


Originally I expected the value selected by default to be the $Type variable. Now I know that's not how selecting options works. But I only know how to select based on knowing the option I want to select. But how would I be able to choose which option gets selected by default based on the value of $Type?

vincevincevince

7:01 pm on Nov 2, 2022 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You need to put 'selected' within the <option> tag.
I would suggest putting the items into an Array, then looping them, with a conditional clause to add 'selected' where it matches $Type.

Approximately...
$Types=Array("Agencies/Offices","Appraisers","........etc.....");
foreach ($Types as $t) print "<option value=\"$t\" ".(($t==$Type)?("selected"):("")).">$t</option>\n";