Skip to main content
Inspiring
October 27, 2016
解決済み

How to use autocomplete to get first and last name from database

  • October 27, 2016
  • 返信数 1.
  • 3106 ビュー

I have tried the cfinput autocomplete and some jquery examples but I just can't get them working.

Does anyone have a full jquery or coldfusion example of how to autocomplete a text field using first and last name pulled from a database?

Thank you!

B.

このトピックへの返信は締め切られました。
解決に役立った回答 BACFL

I was ultimately able to do it with this .cfc

<!--- Lookup used for auto suggest --->

    <cffunction name="lookupname" access="remote" returntype="array">

<cfargument name="search" type="any" required="false" default="">

<!--- Define variables --->

<cfset var data="">

<cfset var result=ArrayNew(1)>

<!--- Do search --->

<cfquery datasource="xxxxxx" name="data">

SELECT lname + ',' + fname as fullname, userid

FROM users

WHERE lname LIKE '#ARGUMENTS.search#%'

ORDER BY lname,fname

</cfquery>

<!--- Build result array --->

<cfloop query="data">

<cfset ArrayAppend(result, fullname)>

<cfset ArrayAppend(result, userid)>

</cfloop>

        <!--- And return it --->

<cfreturn result>

    </cffunction>

   

</cfcomponent>

THE HTML:

<cfform>

<cfinput type="text"

        name="fullname"

        autosuggest="cfc:getname.lookupname({cfautosuggestvalue})">

</cfform>

返信数 1

WolfShade
Legend
October 27, 2016

I recommend not using CFFORM or any CFINPUT, CFSELECT, etc.  The binding can be appealing, but a few more keystrokes can get you better granular control, validation, etc., if done manually.  No veteran developer (that I am aware of) uses CFFORM et al for anything.  It started out as a great idea, but it uses an outdated javascript library that can sometimes glitch up on you.

A standard FORM can do at least as good as, more likely better than, CFFORM, granted it means a little more work on your part (it's totally worth it.)

Basically, using jQuery, you can set the onKeyDown or onKeyPress of the input fields to actuate a function that will use AJaX to send the field value to a CFFUNCTION in a .CFC component file that will query the database (SELECT firstName FROM users WHERE firstName like <cfqueryparam value="#form.firstName#%" /> -- notice the wildcard) and will return a query on each keystroke.  You use the query object converted to JSON to populate a variable and use a jQuery plugin to display the clickable options in an almost drop-down fashion.  jQueryUI has this capability.  Click here for an example.

HTH,

^_^

Legend
October 27, 2016

To expand on what WolfShade said, I recommend looking at jquery.typeahead: GitHub - twitter/typeahead.js: typeahead.js is a fast and fully-featured autocomplete library. It works great with AJAX calls or local data.