Jump to content

how to retrieve selected value for a <select> menu?


ivytony

Recommended Posts

I am wondering how to retrieve the saved selected value for a <select> menu and have it selected as default when editing the selection.

 

For example, there is a select menu that has these values: North America, Asia, Europe, South America, and Australia. You selected 'Asia' when you saved it last time. Now you want to edit this selection, what you shall see is 'Asia' selected by default.

 

Did I make myself clear? Can someone give me some help?

 

 

thanks!

Most the time people post what they tried and try and at least show they attempted to code it themselves.  Not saying its a rule or anything just a helpful tip.

 

If you using the select fields saved from a mysql database you could order them by default_field and put that in a foreach or while i guess.  That would make it easy if thats all you have to do but also kind of lazy way of doing it.

You would do something like this:

 

 

<?php
// This is what the user choose last time, get this from the database or similar
$last_choice = 'North America';

// Array containing all the possible choices for your <select>
$countries = array('North America', 'Asia', 'Europe', 'South America', 'Australia');

// Start the <select>
echo '<select name="country">';

// Loop through the array creating your <option>'s
foreach($countries as $country) {
  
  if($country == $last_choice) {
    echo '<option selected="selected" value="' . $country . '">' . $country . '</option>';
  else {
    echo '<option value="' . $country . '">' . $country . '</option>';
}

// Close the select
echo '</select>';
?>

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.