ColdFusion Ajax Tutorial 2: Related Selects

Home » ColdFusion Ajax Tutorial 2: Related Selects

Many of us have built related select controls, forms with two (or more) drop down control) and the second containing the display text. (For now, this two dimensional array is the format required by ).
Now for the form itself:

Select Media Type:
Select Art:

The form contains two controls, one named “mediaid” and the other named “artid”.
“mediaid” is bound to cfc:art.getMedia(), and so to obtain the list of media types to populate the control, the client makes an asynchronous call to the getMedia method in art.cfc, and populates the list with the returned array. As we’d want this control to be automatically populated when the form loads, bindonload is set to “true&quot, this way the getMedia() call is fired automatically at form load time.
“artid” is bound to the getArt method in art.cfc. This method requires that a mediaid be passed to it, and so {mediaid} is used so as to pass the currently selected value of control mediaid (the first ). Because these two controls are bound together, the second dependant on the first, ColdFusion automatically generates JavaScript code that forces artid to be repopulated with newly retrieved data whenever mediaid changes.
This example binds just two controls, but this mechanism can be used to relate as many controls as needed, and not just controls either.

164 responses to “ColdFusion Ajax Tutorial 2: Related Selects”

  1. Mark Ireland Avatar
    Mark Ireland

    Could there be a JSON version of this? (Where it didnt matter which application server returned the data)

  2. Ryan Mac Donalld / ColdFusion openings in Kansas Avatar
    Ryan Mac Donalld / ColdFusion openings in Kansas

    Position: Cold Fusion Developer
    Location: Kansas City, MO
    Salary: $70,000/year
    Benefits: group health insurance, dental insurance, vision insurance, fitness reimbursement, 401(k) plan, paid vacation and sick time and holidays.
    Work hours are generally 9:00 AM – 5:00 PM. Payroll is paid semi-monthly.
    Start Date: 06/11/07
    Two years of experience designing, developing, maintaining and enhancing Internet site content and applications
    using Web development tools Macromedia’s Dreamweaver or Cold Fusion Studio MX. Must be highly proficient
    with HTML, XHTML, JavaScript, CSS. Experience with Cold Fusion server MX. Experience working in a multi-server
    environment using development, testing, staging and production servers. Experience using FTP,
    VPN, and terminal services clients. Must be experienced with common web browsers, web standards and platform
    specific development issues.
    General Skills:
    Must be self-motivated and able to work with minimal direction.
    Work quickly and efficiently.
    Excellent analytical skills.
    Knowledge of Intel based PC systems.
    Excellent verbal and written communication skills.
    Technical Skills:
    Required skills:
    -ColdFusion MX
    -SQL Server
    Desirable skills:
    -Cold fusion certified
    -Flash MX
    -Flex 2.0
    Ryan Mac Donald
    MegaForce LLC
    7450 West 130th Street / Suite 300
    Overland Park, Kansas 66213
    1-800-676-6625 Ext.309
    913-402-0800 #309
    913-402-8454 – Fax

  3. Sam Farmer Avatar
    Sam Farmer

    You can also bind to a URL, so bind="url:getStates.cfm" just return the array with this:
    And have no other output

  4. Doug Cain Avatar
    Doug Cain

    Hi Ben,
    I just tried the bind example out and it fails with:
    error:http: Error invoking CFC /art.cfc : Error Executing Database Query.
    info:http: HTTP GET /art.cfc?method=getMedia&returnFormat=json&argumentCollection=%7B%7D&_cf_nodebug=true&_cf_nocache=true&_cf_rc=0
    info:http: Invoking CFC: /art.cfc , function: getMedia , arguments: {}
    in the ajax debugger. It seems to be looking for my cfc in / when both files are in my webroot: /localhost/
    This is driving me nuts as I get the same issue trying to bind to a cfc which is in a mapped directory. Hence I went back to your simple example.
    This seems like a bug to me? Anyway any thoughts greatly appreciated.
    Oh i’m running cf8 on vista 32bit..

  5. Ben Forta Avatar
    Ben Forta

    Doug, try invoking those CFCs directly, a straight <cfinvoke> call in a .CFM page. It looks like you are getting a <cfquery> error independent of the Ajax stuff,s o you need to figure that out first.
    — Ben

  6. Doug Cain Avatar
    Doug Cain

    Hi Ben,
    Sorry I noticed that , cf8 didn’t install the sample stuff it seems. Fixed that by grabbing the cf7 one. I have solved my problem though, I was sending parameters as you would if calling the cfc by url id=1&lang=2 etc when it should be id=1,lang=2.
    Doesn’t work:
    <cfselect bind="cfc:org.survey.api.getChildren(orgid=1&surveyid=2)"
    <cfselect bind="cfc:org.survey.api.getChildren(orgid=1,surveyid=2)"
    Simple in the end as ever! Thanks for the quick response.

  7. Matt F. Avatar
    Matt F.

    Thanks for the tutorial, I just finished a State / City select chain using it. One problem I am having is with speed. My initial states select box populates very quickly but the query of the cities takes up to 30 seconds. The query itself is very snappy. Any ideas on helping me speed this up?
    Thanks so much.

  8. Ben Forta Avatar
    Ben Forta

    Matt, try calling the City CFC method yourself, from a <CFINVOKE>, and see how it performs. Then try it also from a URL setting RETURNFORMAT="json", and see how that performs.
    — Ben

  9. Matt F. Avatar
    Matt F.

    Hey Ben,
    <!— CFINVOKE —>
    origin_state_id = "1"
    <cfdump var="#origin_city#">
    3532 ms
    <!— URL CALL —>
    36 ms
    I used CFINVOKE and it returns the query in 3532 ms and takes about 10-12 seconds to actually fully display the page. I called it from the url using RETURNFORMAT="json" like you suggested and it returned in 36ms… much faster. Does this bring anything to light?
    Thanks for your help!

  10. Chris Avatar

    When working with this example, I get the following error in the AJAX debug window
    "window:global: Exception thrown and not caught"
    Any ideas? I have stripped everything down to a cfselect that calls a function that I have verified that works. In fact, it’s resulset populates in the debug window, but my select isn’t populated with it’s resultset.

  11. Jeremy Rottman Avatar
    Jeremy Rottman

    I am playing around with my new coldfusion 8 install. I am trying to use your example to bind data from two of my cfc’s But for some reason, my tests don’t work at all. It does not populate any of the inputs and gives no errors
    Here is the code I am using
    <td>Select Media Type:</td>
    <td><cfselect name="catUUID"
    bindonload="true" /></td>
    <td>Select Art:</td>
    <td><cfselect name="secUUID"
    bind="cfc:com.UtilityManager.List_Sections({catUUID})" /></td>
    Function: List_Categories
    <cffunction name="List_Categories" access="remote" output="false" returntype="array">
    <cfquery name="GetCats" datasource="#this.DSN#">
    fld_category_UUID as catUUID,
    fld_category_Name as catName,
    fld_category_Order ASC
    <cfset catArr = arrayNew(1)>
    <cfset i = 1>
    <cfloop query="GetCats">
    <cfset catArr[i] = structNew()>
    <cfset catArr[i].catUUID = GetCats.fld_category_UUID>
    <cfset catArr[i].catName = GetCats.fld_category_Name>
    <cfset catArr[i].catAlias = GetCats.fld_category_Alias>
    <cfset i = i + 1>
    <cfreturn GetCats />
    Function: List_Sections
    <cffunction name="List_Sections" access="remote" output="false" returntype="array">
    <cfargument name="catUUID" required="yes" type="string" />
    <cfquery name="GetSections" datasource="#this.DSN#">
    fld_category_UUID = <cfqueryparam cfsqltype="cf_sql_varchar" value="#arguments.catUUID#" />
    <cfset secArr = arrayNew(1)>
    <cfset i = 1>
    <cfloop query="GetSections">
    <cfset secArr[i] = structNew()>
    <cfset secArr[i].secUUID = GetSections.fld_section_UUID>
    <cfset secArr[i].secName = GetSections.fld_section_Name>
    <cfset secArr[i].secAlias = GetSections.fld_section_Alias>
    <cfset secArr[i].catUUID = GetSections.fld_category_UUID>
    <cfset i = i + 1>
    <cfreturn secArr />

  12. Scott Terrell Avatar
    Scott Terrell

    Hello Ben,
    Thanks for your wonderful example and dedication to CF. I’m trying to get the basic example of related selects to work using CF8 and binding.
    I get the following: "exception thrown and not caught" It does not seem to matter if I bind using cfc or url. I can hit the cfc directly via a url and it works fine. Any help would be appreciated.
    <cfcomponent output="no">
    <cfset THIS.dsn="axdealer">
    <!— Get array of media types —>
    <cffunction name="getMedia" access="remote" returnType="query">
    <!— Define variables —>
    <cfset var data="">
    <!— Get data —>
    <cfquery name="data" datasource="#THIS.dsn#">
    SELECT Country_ID as CountryID, Country_Name as CountryName
    FROM Countries
    ORDER BY Country_Name
    <!— And return it —>
    <cfreturn data>
    <td>Select Media Type:</td>
    <td><cfselect name="mediaid"
    bindonload="true" method="remote" /></td>

  13. K0rrupt Avatar

    I used this and it works great on a test site i got, but when i add it to the site i’m working on my Application.cfc onRequestStart / onRequestEnd cancels it out. any idea why?
    <cfcomponent output="no">
    <cfset = "reg.securitycode" />
    <cfset THIS.sessionmanagement=true />
    <cfset THIS.dsn = "aiya_ca" />
    <cffunction name="onRequestStart" returntype="boolean" output="true">
    <!— DIsplay the header.cfm —>
    <cfinclude template="../includes/Header.cfm"/>
    <cfreturn true />
    <cffunction name="onRequestEnd" returntype="void" output="true">
    <!— Display Footer.cfm —>
    <cfinclude template="../includes/Footer.cfm" />

  14. Kasey Koester Avatar
    Kasey Koester

    I’m having trouble putting this example code up on my server. I keep getting this error: Error invoking CFC /art.cfc: Not Found
    Any suggestions on what I’m doing wrong?

  15. Jainee Avatar

    Hi! Ben,
    Thanks for your tutorial. The newly created bound selection boxes work perfect when I browse direct on our intra net but it will not working at all when browse through VPN. Do you ware of the problem? Any advice? I really like the new feature and don’t want drop it due to VPN compatible issue.

  16. Sharad Avatar

    Hi Ben,
    Thanks for the example…but i have some problem executing it with Fusebox 4.
    I use following code in fusebox.init.cfm
    <cfset application.tryajax = createObject( ‘component’, ‘#REQUEST.cfcPath#.cfcs.testajax’ ).init() />
    And then in calling page…
    <cfselect bindonload="true" bind="application.tryajax.agnt()" name="agent_code" multiple="true" size="4">
    it do not recognise line…
    i tried …
    then it cannot locate tryajax CFC.

  17. Michael Brennan-White Avatar
    Michael Brennan-White

    Instead of sending the selected item from the first select box to the bind of the second select, is there a way of passing the first value as a CFgrid Argument.

  18. Scott Terrell Avatar
    Scott Terrell

    How would you go about defaulting values to the related selects.

  19. Scott Terrell Avatar
    Scott Terrell

    Has anyone been able to use the related selects (bound to a cfc) and set a default value (as if editing an existing record)?

  20. David Graham Avatar
    David Graham

    Ben and All – As always – thanks for all your help.
    This may seem simple – but I’m trying to persist the selected values in a form when posting back to the same page. Here’s what I have:
    (1) HTML SELECT – static values
    (2) CFSELECT bound to (1)
    (3) CFSELECT bound to (2)
    (4) CFSELECT bound to (2)
    On repost NONE of the values in 2, 3, or 4 are selected (though they are correct in the FORM). What am I missing? It looks like cfform.persistData and cfselect.selection handle this when using the query attribute…

  21. Mike Demahy Avatar
    Mike Demahy

    Any luck solving the problem of "window:global: Exception thrown and not caught ". I have seen lots of posts for this but no resolutions.

  22. Jason Presley Avatar
    Jason Presley

    I put both of these files (form.cfm & art.cfc) into my root folder which I have set up on a flash drive and mapped to using IIS (which has CF installed into it). I tried calling the form.cfm page and get this error:
    error:http: Error invoking CFC /art.cfc : Not Found
    info:http: HTTP GET /art.cfc?method=getMedia&returnFormat=json&argumentCollection=%7B%7D&_cf_nodebug=true&_cf_nocache=true&_cf_clientid=1F0E1972D346E48FF8BE4E01B50D62DE&_cf_rc=0
    info:http: Invoking CFC: /art.cfc , function: getMedia , arguments: {}
    info:LogReader: LogReader initialized
    info:global: Logger initialized
    If I change the path I get even more of an error. Is there an issue with the / that is showing in front of the art.cfc? Why is this saying that it can’t find the cfc.
    My local url is: http://localhost/liquidfusiondemo
    I have tried binding the cfc to the cfselect in the following ways:
    Any help with this path issue would be appriciated!

  23. Tony McCormick Avatar
    Tony McCormick

    I got this to work well in HTML forms mainly for Country, State, Town bound dropdowns.
    My problem:
    How can I get it work in a Flash form – I’ve tried every combination and thechnique I can think of – it doesnt throw an error, just no results.
    I can get it to work with straight drop downs accessing CF queries for each cfselect but I can’t get it to work as "bound" fields in a Flash form using a cfc that works in HTML
    I’d be grateful for any clues.

  24. Jim Avatar

    Is there an answer for the binding problem that many of us are having in CF 8? Using your simple autocomplete code I get this error:
    window:global: Exception thrown and not caught in the ajax cfdebug window
    This is the complete ajax cfdebug out which shows that the data is returned but never loaded into the control:
    window:global: Exception thrown and not caught (, line 787)
    info:http: CFC invocation response: "Beauty,Blue Moon,Bowl of Flowers"
    info:http: HTTP GET /test/art.cfc?method=lookupArt&returnFormat=json&argumentCollection=%7B%22search%22%3A%22B%22%7D&_cf_nodebug=true&_cf_nocache=true&_cf_clientid=5B3D4FB5A704B1B07324B62723A43911&_cf_rc=2
    info:http: Invoking CFC: /test/art.cfc , function: lookupArt , arguments: {"search":"B"}
    info:widget: Fetching data for autosuggest id: artname , current value: ‘B’
    Please help. – Jim

  25. Ben Forta Avatar
    Ben Forta

    Jim, I have asked the engineering team to look into this one too. I’ll post a response when I hear something useful.
    — Ben

  26. Tony McCormick Avatar
    Tony McCormick

    Hi Ben
    Love reading your stuff and this has been most useful.
    Will your example work in a Flash form?
    How do you get your example to work in a flash form?
    I’ve fiddled with the syntax in cfselect and get nothing – not even errors.
    I’ve not used a lot of Flash but I’m trying to use it to make it harder for hacks and snoops to find the names of variables passed in forms.
    Id be most grateful if you could show the changes in cfselect to do this.
    Tony McCormick

  27. Ak Avatar

    I am getting error on 2nd box bind: "Bind failed. Element not found: subcat_key"
    I can’t figure it out, been trying for an hour now! This is my code:
    <cfcomponent output="false" >
    <cfset THIS.dsn="NJDB">
    <!— Get array of media types —>
    <cffunction name="getcat" access="remote" returnType="array">
    <!— Define variables —>
    <cfset var data="">
    <cfset var result=ArrayNew(2)>
    <cfset var i=0>
    <!— Get data —>
    <cfquery name="data" datasource="#THIS.dsn#">
    SELECT cat_key, cat
    FROM tb_includes_cat
    ORDER BY cat
    <!— Convert results to array —>
    <cfloop index="i" from="1" to="#data.RecordCount#">
    <cfset result[i][1]=data.cat_key[i]>
    <cfset result[i][2][i]>
    <!— And return it —>
    <cfreturn result>
    <!— Get art by media type —>
    <cffunction name="getSubCat" access="remote" returnType="array">
    <cfargument name="cat_key" type="numeric" required="true">
    <!— Define variables —>
    <cfset var data="">
    <cfset var result=ArrayNew(2)>
    <cfset var i=0>
    <!— Get data —>
    <cfquery name="data" datasource="#THIS.dsn#" >
    SELECT subcat_key , subcat
    FROM tb_includes_subcat
    WHERE cat_key = #ARGUMENTS.cat_key#
    ORDER BY subcat
    <!— Convert results to array —>
    <cfloop index="i" from="1" to="#data.RecordCount#">
    <cfset result[i][1]=data.subcat_key[i]>
    <cfset result[i][2]=data.subcat[i]>
    <!— And return it —>
    <cfreturn result>
    <cfoutput query="data">#subcat# – #subcat_key#</cfoutput>
    <td>Select Media Type:</td>
    <td><cfselect name="Cat"
    bindonload="true" /></td>
    <td>Select Art:</td>
    <td><cfselect name="subCat"
    bind="{subcat_key})" /></td>

  28. Wendy Avatar

    Is there any samples with using the cfselect with more than 2. I haven’t been able to get anything more than 2 to work regardless if I use queries, or arrays in the cfc page. Is there some sample I can review that shows three related cfselects working? I’ve posted this on adobe’s cf forums and haven’t received any posts. I’m pulling my hair out.

  29. Jared Avatar

    Many people in these threads are getting the error listed below:
    window:global: Exception thrown and not caught (<url>, line 787)
    The reason for this is because although you are calling a CFC, your are ultimately sending a full HTTP GET request to the server. In doing so, application.cfm/application.cfc is still being processed. If you are including ANY content via application.cfm/cfc, then your call via AJAX is actually returning the result of the CFC function as well as all content being included in your requests….
    The workaround that Im using is to check the value of the CGI.SCRIPT_NAME and if it ends w/ cfc, DONT include any content… that way your CFC is only returing the data that you want returned.
    Oh yeah… make sure its in JSON format (SerializeJSON)….
    Happy coding 🙂

  30. james Avatar

    Just to follow up on a topic that I have seen in multiple threads here (and a problem I was having). Trying to get the multiple selects to work, I was getting an error saying that the cfc could not be found. I have all my components and display pages outside of webpages and can invoke all cfcs without a problem, but when it came to trying to get "ajax" to invoke the cfc no luck.
    This is very disappointing and I was wondering if there was a reason for this and if this will be changed in subsequent updates?
    I have used cfajax from without any problems and will continue to do so as I can not, and frankly don’t want to, change the structure of my files.
    So for anyone else having problems, for me I had to move all my display and cfc files inside of webpages and then that worked for me.
    As always Ben thanks for your continued effort and great work.

  31. Ken Teegardin Avatar
    Ken Teegardin

    I copied the "Using Binding-pg361) example in your book (CF8-getting started) and was able to get it working with no problems. Now I need to do something with the values. I tried passing them using a form submit but that results in an Ajax error.
    How do I access the values from my bound listboxes once someone has selected them and submitted the form?
    Is there some simple way to use #form.listboxname#?

  32. Raymond Camden Avatar
    Raymond Camden

    Hey Ken – I may not be reading you right. But when you submit the form, it should indeed be available as form.whatever. Have you tried cfdumping the form scope to see all the values?

  33. Matt Bennett Avatar
    Matt Bennett

    I’m trying to add an <option> tag into the code below:
    <td>Select Media Type:</td>
    <td><cfselect name="mediaid"
    bindonload="true" /></td>
    <td>Select Media Type:</td>
    <td><cfselect name="mediaid"
    bindonload="true" />
    <option value="">—All Media—</option>
    This scenario works great when you populate the cfselect with a query, and allow you to put the option up at the top. When I’m using the cfc and binding, this isn’t showing up. Thoughts on how to make this work. Ideally the option tag would be the first option to come up (top).
    Thanks! Matt

  34. Jared Avatar

    Try manually inserting a blank record into it inside of your CFC 😉

  35. Matt Bennett Avatar
    Matt Bennett

    Just in case anyone wanted the code:
    <CFSET sortArray = ArrayNew(1)>
    <CFSET QueryAddColumn(data, "sort_order", sortArray)>
    <CFSET QueryAddRow(data)>
    <CFSET QuerySetCell(data, "MediaType", "")>
    <CFSET QuerySetCell(data, "sort_order", 1)>
    <CFQUERY NAME="querySorted" DBTYPE="Query">
    SELECT * FROM data
    ORDER BY sort_order desc, Category asc
    <CFRETURN querySorted>

  36. Will Swain Avatar
    Will Swain

    Hi Ben,
    I’m using your example code and having a problem:
    It works fine on my local server cf8 enterprise. Nothing is returned on my production server, cf8 standard. Using Firebug I can see that the call to the cfc is correct, but the response is empty. No error is being thrown. Any suggestions. (BTW, I’ve had similar problems with binding to a cfgrid too.)
    <cfselect name="operaID"
    <cfselect name="perfID"
    bind="cfc:#application.cfc_root#perfs.getPerfs({operaID})" />

  37. Raymond Camden Avatar
    Raymond Camden

    Do you have an Application.cfc in play? One with an onRequest method?

  38. Ben Forta Avatar
    Ben Forta

    Will, sounds like it may be the virtual directory bug, which is supposed to be fix in the updater due out shortly.
    — Ben

  39. Will Swain Avatar
    Will Swain

    @Ray, yes – have tried commenting it out but no change
    @Ben – ah – is this a known bug then? Is there somewhere I can find more detail about it to check against my scenario? Also, if I bind to a .cfm will I get the same problem?

  40. Franklin Aizpurua Avatar
    Franklin Aizpurua

    Hello Ben,
    I’m having trouble when I try to use more than 2 related cfselects.
    Now I’m working in a Page with 5 related cfselect for country, state, county, city, street
    and because the cfc functions are invoked more than once when you change the country or state for example, the page loads the data very slowly.
    When I change the value on the first one, it invokes de cfc function for the other cfselects, but at the same time since the 2nd cfselect is changing it reinvokes again all the cfc functions of the cfselects that are related to him and so on, making the last one call the cfc function for each time the cfselects before him changed
    How can I work aroud that?
    Here is a example of my cfselects and the way the binds are related
    <cfselect name = "country"
    required = "Yes"
    message = "some text"
    value ="ID"
    display="NAME" >
    <cfselect name = "state"
    required = "Yes"
    message = "some text"
    <cfselect name = "county"
    required = "Yes"
    message = "some text"
    bind="cfc:cfc.getData0035(‘#dtsource#’,{country},{state})" >
    <cfselect name = "city"
    required = "Yes"
    message = "some text"
    bind="cfc:cfc.getData0045(‘#dtsource#’,{country},{state},{county})" >
    <cfselect name = "street"
    required = "Yes"
    message = "some text"
    bind="cfc:cfc.getData0051(‘#dtsource#’,{country},{state},{county},{city}) >
    The query results are not big so it should be fast if I can avoid calling the cfc functions more times than needed.

  41. Jared Shields Avatar
    Jared Shields

    I’m not sure if the "onChange" event is fired when the options inside of a select box are alters (but not the selection changed, but you could try appending @change to the end of each of your bind variables
    Thanks might work.

  42. Franklin Aizpurua Avatar
    Franklin Aizpurua

    Thanks for the idea Jared,
    Unfortunately it doesnt work that way, it seems the "onChange" event is fired and because of that the binds keep calling the cfc.
    Any other ideas will be appreciated.

  43. Paul Avatar

    I have adapted this example to work with 3 selects (the 3rd select being dependant on the second).
    I am wanting to hide the second and third selects when no value has been selected from the first and hide the 3rd select when no value has been selected from the second.
    I have been trying to get this working, but cannot find a way to intercept and use the results coming back in the bind i.e. if no results found, hide the relevant select.
    Any ideas any one?

  44. tim Avatar

    Your bind example works great, but I have one thing that i can’t figure out. When you populate a cfselect using a query you have the selected="#FORM.inputName#" to select an option when editing a record. However, when you bind these select boxes I cannot figure out how to get my user’s selection to stay selected in the event of a form error – such as other required fields that were left blank and still need to be filled out- or editing a record to reselect their previous selection that has been stored in the database. I am binding two select boxes one with a list of countries and the other with active states/provinces. I tried sending those selections as arguments to the cfc, but that simply limited my returned query only to those single records not allowing them to change their selection. Any help/suggestions to help me figure out how to maintain these user selections would be appreciated.

  45. Franklin Aizpurua Avatar
    Franklin Aizpurua

    Hello all, I found the answer to my problem and decided to share it here.
    When i used 2 or more cfselet with related binds the binds called de cfc component for every value that changed.
    To avoid that use @none in the bind values, that way only the values without the @none will trigger the bind event, but will send all the variables to the cfc
    As an example: the county cfselect need the values from the country and state cfselects, but will only refresh the data when the state cfselect change value
    <cfselect name = "county"
    required = "Yes"
    message = "some text"
    bind="cfc:cfc.getData0035(‘#dtsource#’,{country@none},{state})" >

  46. Arowolo M. Avatar
    Arowolo M.

    hi tim,
    i have been looking for the solution to the problem of bind and selected attributes. after 30 min of search i decide to hack the thing myself.
    <!— function to bind to —>
    <cffunction name="ajEmployeeLookUp" access="remote" returntype="array">
    <cfargument name="SelectedId" default="0" required="yes" />
    <!— get all the record first —>
    <cfquery name="qTemp" datasource="dsn">
    SELECT Employee,Name
    FROM Employee
    <!— get the selected rec. using Query of Query —>
    <cfquery name="qSel" dbtype="query">
    SELECT * FROM qTemp WHERE EmployeeId = #arguments.SelectedId#
    <!— requery and remove SelectedId from ur ressult —>
    <cfquery name="qTemp" dbtype="query">
    SELECT * FROM qTemp WHERE EmployeeId <> #arguments.SelectedId#
    <cfset i=1/>
    <cfset a=ArrayNew(2) />
    <!— set the selected item first, since thats what the browser will choose first —>
    <cfset a[1][1] = qSel.EmployeeId />
    <cfset a[1][2] = qSel.Name />
    <cfloop query="qTemp" >
    <cfset i=i+1 />
    <cfset a[i][1] = EmployeeId />
    <cfset a[i][2] = Name />
    <cfreturn a />
    <!—- your .cfm page —>
    <!— the selected id can be from a url, form or query. —>
    <cfselect name="Employee" bind="cfc:Employee.ajEmployeeLookUp(#selectedid#)" />
    that might not be too clean but it does the work.
    i will try and work on a better hack.

  47. James Avatar

    I wanted to add another way to get the second related drop down to be prepopulated.
    Again this is a bit of a hack, but works for now. This is combining something that I read on Raymond Camden’s site ( and Ben’s example.
    Simply put, you use cfajaxproxy to check to see when the first select has loaded and then call some simple Javascript that loops over the options in the select and marks the one that you want as selected.
    I’d love for their to be a better way, so if there is please someone educate me 🙂
    <cfajaxproxy bind="cfc:cfc.getClientContacts({contactID.value})" onSuccess="preselected">
    function preselected(){
    preSelectedContactID = document.formName.preSelectedContactID.value;
    for(var i=0;i<document.formName.contactID.options.length;i++){
    if(preSelectedContactID == document.formName.contactID.options[i].value){
    document.formName.contactID.options[i].selected = true;
    <cfform name="formName">
    <input type="hidden" name="preSelectedContactID" value="#attributes.query.contactID#">
    <cfselect name="clientid"
    selected="#attributes.query.clientID#" />
    <cfselect name="contactID" multiple="false" size="1"
    display="lastFirst" />

  48. elaine Avatar

    <cfselect name="mediaid"
    bindonload="true" />
    How do you set the initially selected item?
    I tried:
    <cfselect name="mediaid"
    But it didn’t work. Does selected work with cfselect and bind?

Leave a Reply