Programming Advisory: Dropdown Tuning August 2, 2019

When presenting a short list of options, the <select> tag is often used. When building user interface for creating a new record, and one that edits an existing record, there are subtle differences to pay attention to.

Consider the scenario when a user if creating a new record. The options are A, B and C:

<select>

<option value="A">A</option>

<option value="B">B</option>

<option value="C">C</option>

</select>

By default, Option A is selected - this could be problematic because a careless user may skip over this field. Option A has a higher chance of being mistakenly selected. It is therefore recommended to add a black option:

<select>

<option value=""></option>

<option value="A">A</option>

<option value="B">B</option>

<option value="C">C</option>

</select>

When the user is editing an existing record, however, the blank option could cause issue. The value of the said field must be one of A, B, C, or D. By the time a record is created, its option is already known. The following code selects the option that is previously stored in the database:

//...

$option=$myrow['option'];

//...

?>

<select>

<?

foreach ($opts as $opt=>$label){

?>

<option value="<?echo $opt;?>" <?if ($opt==$option) echo 'selected';?>>

    <?echo $label;?>

</option>

<?

}//foreach

?>

</select>

In an interface for editing, the dropdown should not allow the end user to change to option back to unknown. Hence the blank option should be removed... or should it?

So far the above two scenarios are common implementations. But we can do better. Remember in a realistic and ever changing software product, the data is often not as clean as we want. What if an Option E is mixed in the data for legacy reasons, and the new interface is phasing it out?

The code above will fail to select Option E, leaving Option A seemingly selected - this is dangerously misleading.

An elegant solution is to show the blank field only if the stored value is not part of the listed options:

<select>

<? if (!in_array($option,$opts)){?>

<option value=""></option>

<?

}

foreach {...

Our Services

Targeted Crawlers

Crawlers for content extraction, restoration and competitive intelligence gathering.

Learn More

Gyroscope™ ERP Solutions

Fully integrated enterprise solutions for rapid and steady growth.

Learn More

E-Commerce

Self-updating websites with product catalog and payment processing.

Learn More