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!

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

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>';
?>

 

 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.