Ashley Sheridan​.co.uk

Creating Select Lists with Default Options

Posted on

Tags:

Select lists are great, but what happens when your visitor has made a mistake in the form and you need to re-display the form, along with the option they just selected? This is where PHP, comes in.

Now, depending on how your site is set up, you might be creating the select list from either a database or other source, but at some point it will be in a form that you can loop though. For this example, I'll be using an array.

<?php $chosen_colour = (isset($_GET['chosen_colour']))?$_GET['chosen_colour']:''; $colours = array('red', 'green', 'blue', 'yellow', 'orange', 'teal'); $html = '<select name="colour">'; for($i=0, $i<count($colours); $i++) { $selected = ($chosen_colour == $colours[$i])?'selected="selected"':''; $html .= "<option value=\"{$colours[$i]}\" $selected>" . ucfirst($colours[$i]) . ''; } $html .= ''; echo $html; ?>

Line 2 picks out the colour from the $_GET array if it is set, or sets it to an empty string if not. Because of the way in which this variable is being used in the script, there is no danger that it can be abused so it doesn't need to be escaped with a function like mysql_real_escape_string().

The array of colours here is just a simple numerical index array, but it could as easily be an associative array, and only needs a minor alteration to the loop.

Line 9 is what does most of the work. It uses the shorthand tertiary operator to create a string based on whether the current item in the loop matches that chosen by thew user. If it does it sets the string to the proper full syntax of selected="selected". This is important if you are going to be using this code in XHTML documents, but it will work perfectly well in plain old HTML documents too.

To make the list look a bit nicer to the visitor, I've capitalised the colour name in the <option> tag, but it could by the key of an associative array if you went down that route.

All of the HTML is bundled up into the $html variable, which you can use at any point later on in your code.

Comments

Leave a comment