Jump to content

[SOLVED] An easy way to automatically do <SELECT>


grissom

Recommended Posts

Hello all

 

I've written a bit of PHP to echo out a bit of HTML on the fly to create a drop down list, a bit like this :

 

echo "
<SELECT NAME = 'mylist'>
<OPTION VALUE = 'whisky'>Jack Daniels
<OPTION VALUE = 'rum'>Havana Club
<OPTION VALUE = 'beer'>Budweiser
</SELECT>";

 

Ok that's going fab.  Now I'd like to insert a SELECTED command into the HTML based on the value of a PHP variable

 

For example, if I had a PHP variable $my_favourite_drink = 'beer'

 

then when the HTML did the drop down list, it would automatically do

 

<OPTION VALUE = 'beer' SELECTED>Budweiser

 

when it got to the appropriate value based on whatever $my_favourite_drink was.

 

I can think of loads of long-winded ways to do it, but there has to be a really smart way that doesn't involve loads of code. Help !

 

All the best and many thanks

Link to comment
Share on other sites

<?php

echo "<select name= 'mylist'>\n";
echo "  <option value='whisky'" . ($my_favourite_drink == 'whisky' ? " selected='selected'>" : ">") . "Jack Daniels";
echo "  <option value='rum'" . ($my_favourite_drink == 'rum' ? " selected='selected'>" : ">") . "Havana Club";
echo "  <option value='whisky'" . ($my_favourite_drink == 'beer' ? " selected='selected'>" : ">") . "Budwieser";
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.