Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How do I dynamically populate a <select> drop-down using <cfselect>?

Dynamic Population

How do I dynamically populate a <select> drop-down using <cfselect>?

by  ecobb  Posted    (Edited  )
[color red] **NOTE: <cfselect> will only work with <cfform>[/color]

The <cfselect> tag is used to dynamically populate a <select> box without the use of any "option" tags. It is a very simple and straightforward tag to use, and it saves a lot of time.

Query the database to get the list of items you want to display in the <cfselect> box.
[color maroon]
<cfquery datasource="#data# name="query_name">
SELECT Display, Value
FROM YourTable
ORDER BY Whatever
</cfquery>
[/color]
Then, use your <cfselect> tag to display all items returned from the query.
[color maroon]
<cfselect name="ItemName" query="query_name" value="Value" display="display"></cfselect>
[/color]
That's it. Pretty simple, huh?

Another cool feature of <cfselect> is that you have the "selected" attribute. This allows you to choose what the default value is in the <cfselect> box, which can be very useful when returning numerous results from your query. For example, if you have a list of Countries in alphabetical order and you didn't want the user to have to scroll to the bottom of the list for "United States", you could specify it as your "selected" and it would be the default country in your list.

Let's say this query pulls the records "Abb" (abbreviation) and "Country" from a database. For the sake of this example, we will say that the abbreviation for United States is "US".
[color maroon]
<cfquery datasource="#data# name="get_countries">
SELECT Abb, Country
FROM Countries
ORDER BY Abb
</cfquery>
[/color]
Then, use your <cfselect> tag to display all items returned from the query.
[color maroon]
<cfselect name="Abb" query="get_countries" value="Abb" display="countries" selected="US"></cfselect>
[/color]
The above <cfselect> tag will return all countries listed in the database (displaying the country name but using the abbreviation as the value), and have "United States" selected as default.

As I said before, this is a very simple and straightforward tag to use, and it saves a lot of time. With just a few clicks you can easily dynamically populate a <select> box.
Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top