Set <select> option selected using PHP



I have written some php code that displays a dropdown list and when the
user selects a value from the list and clicks the "Go" button, the form
displays a filtered database view based on the selection.

Once the user clicks the "Go" button, the filtered records are displayed correctly,
But how do I set the appropriate selection in the dropdown box to be showing.
Right now, it defaults back to the first option value as I am not sure how to do this.

Any help, much appreciated.

Javascript code:
function FilterSchools(selectObject)
    var value = selectObject.value;  
    document.getElementById("ftype").value = value;

function xxx_schools_list() 
    <link type="text/css" href="<?php echo WP_PLUGIN_URL; ?>/xxx-schools/style-admin.css" rel="stylesheet" />
    <script language="JavaScript" src="<?php echo WP_PLUGIN_URL; ?>/xxx-schools/tenders.js"></script> 

    <div class="wrap">
        <h2 style="font-size:28px;color:#0c6bb5;">School List</h2>
        <div class="tablenav top">
            <div class="alignleft actions">
                 <form name="Form1" action="" method="POST">
	<select name="filter" onchange="FilterSchools(this)">
	<option value=''>All</option>
	<option value='Open'>Open</option>
	<option value='Closed'>Closed</option>
	<option value='Awarded'>Awarded</option>
	<option value='Archived'>Archived</option>
	<option value='Cancelled'>Cancelled Tenders</option>

	<input type="text" id="ftype" name="ftype">
                 <input type="submit" class="fbutton-small" value="GO">
            <br class="clear">

        global $wpdb;

        $sFilter 	          	=  $_POST["ftype"];
        $_SESSION["filterby"] 	= $sFilter;

        $table_name  = $wpdb->prefix . "school";

        if ($sFilter == '')
	  $rows 	= $wpdb->get_results("SELECT * from $table_name ORDER BY id");
	  $rows 	= $wpdb->get_results("SELECT * from $table_name  WHERE status = '$sFilter' ORDER BY id");


        <table class="wp-list-table widefat fixed striped posts" width=100%>

            <?php foreach ($rows as $row) 
                    <td><?php echo $row->id; ?></td>
                    <td><?php echo $row->name; ?></td>
                    <td><?php echo $row->type; ?></td>
                    <td><?php echo $row->issued; ?></td>
                    <td><?php echo $row->closed; ?></td>
                    <td><?php echo $row->status; ?></td>
                    <td><?php echo substr($row->desc, 0, 60); ?></td>
                    <td><a href="<?php echo admin_url('admin.php?page=xxx_schools_update&id=' . $row->id); ?>">Update</a></td>
            <?php } ?>



When you draw the options, you need to look at the value of the selection as passed into your page, and add the "selected" keyword. It might be easier if the options were displayed from a database, you could just then compare the values as you're looping through. As they seem to be hard-coded, then the check will need to be hard-coded.

You need to retrieve your $sFilter variable before you draw the options list, rather than after it as you do now. Is there a reason that you use JavaScript to trap the option selection and then stick the value in a text input, rather than just using the option value directly?


Usually you would have php render the options from an array and check the value against your filter, adding selected if they match.


You might define the options something like this, either hard coded or pulled from a database.

$options = array(
  'All' => '',
  'Open' => 'Open',
  'Closed' => 'Closed',
  'Ararded' => 'Awarded',
  'Archived' => 'Archived',
  'Cancelled Tenders' => 'Cancelled',

And set your default:-

if(isset($_POST['filter'])) { $filter = $_POST['filter'] ;} // set the filter if set
else{ $filter = 'All' ;}  // Have the default fall-back

Now you can have a function make the options:-

function makeopts($options, $default){ // Using a function to keep the html tidyer
  $html = '';  // Start the html blank
  foreach($options as $name => $value) { // Go through the array of options
    if($value === $default){ $sel = ' selected' ;}  // Check the value against the filter (default)
    else{ $sel = '' ;} // Set an empty fall=back
    $html .= "\t<option value='$value'$sel>$name</option>\n" ; // Create the html code
  return $html ; // and return

Call the function in the html:-

<?= makeopts($options, $filter) ?>

That's just one way*...
You may want to escape the values/names, depending where it comes from.
*Not tested!


Thank you all for your input.
Very helpful.


Here is another from @gandalf458

and another verbose solution


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.