Thursday, October 31, 2013

Bind data to an input field via autosuggest using data from another input field.

 here is my first input:

   <cfinput type="text"
        name="country" value="#form.country#" validateat="onSubmit" size="60" showAutoSuggestLoadingIcon="false"
        autosuggest="cfc:ajaxlookup.getCountries({cfautosuggestvalue})">


This is a simple CF autosuggest. It calls the getCountries function in the  ajaxlookup cfc. The CFC is in the same directory as my file. I don't know if you have to do this but it just works better for me. :)

This call will suggest countries as the person types the name of the country.

(showAutoSuggestLoadingIcon="false" means that little loading icon won't show.)

Here is the getCountries function:

 <!--- Country Lookup used for auto suggest --->
<cffunction access="remote" name="getCountries" output="yes" returntype="array">
<cfargument name="search" type="any" required="false" default="">
<!--- Define variables --->
<cfset var data="">
<cfset var result=ArrayNew(1)>
<!--- Do search --->
<cfquery datasource="#request.dsn#" name="data">
SELECT     strCountry
FROM tblCountries
WHERE strCountry LIKE '#arguments.search#%'
ORDER BY strCountry
</cfquery>
<!--- Build result array --->
<cfloop query="data">
<cfset ArrayAppend(result, strCountry)>
</cfloop>
<!--- And return it --->
<cfreturn result>
    </cffunction>
   

So I want to send the country ID to the database, not the country name. So I am going to retrieve the country ID based on the country that the user selected in the above input.


Here is my 2nd input:


<cfinput type="hidden" name="countryID" id="countryID" bind="cfc:ajaxlookup.getCountryID({country})">

It uses the bind attribute to call the getCountry method while passing in the value of the country input.

Enjoy!

No comments:

Post a Comment