JQuery autocomplete does not display text values but fills in elements
I have jQuery autocomplete which works fine, except that it does not correctly display the text values returned by the function. My backend is ColdFusion.
Backend Function (in CFC):
<cffunction name="companyNameList" access="remote" output="false" hint="I return a list of companies with IDs" returnformat="JSON">
<cfargument name="searchterm" required="false" default="" />
<cfset var returnArray = arrayNew(1) />
<cfquery name="companyNameList" datasource="#request.dsn#">
SELECT companyID, companyName
FROM tbl_companies
WHERE companyName LIKE <cfqueryparam cfsqltype="cf_sql_varchar" value="%#arguments.searchterm#%" />
</cfquery>
<cfloop query="companyNameList">
<cfset companyStruct = structNew() />
<cfset companyStruct['value'] = companyID />
<cfset companyStruct['label'] = companyName />
<cfset arrayAppend(returnArray,companyStruct) />
</cfloop>
<cfreturn returnArray />
</cffunction>
My jQuery jQuery (it's wrapped in cfoutput tags, which requires a second hash mark as the escape value):
$(function() {
$("##defaultcompanyname").autocomplete({
source: function(request, response){
$.ajax({
url: "secure/cfc/ajax.cfc?method=companyNameList",
dataType: "json",
data: {
searchterm: request.term
},
success: function(data){
response(data);
}
})
},
minLength: 3,
select: function(event, ui) {
$('##defaultcompanyid').val(ui.item.value);
$('##defaultcompanyname').val(ui.item.label);
}
});
});
And the corresponding form block:
<p class="ui-widget">
<label for="defaultcompanyname">Default Company Association</label>
<cfinput type="text" size="30em;" name="defaultcompanyname" id="defaultcompanyname" value="" />
<cfinput type="hidden" name="defaultcompanyid" id="defaultcompanyid" value="0" />
</p>
When I use the type in 'test' as my test value, this is the JSON returned:
[{"value":2,"label":"Test Company"},{"value":3,"label":"2nd Test Company"}]
The list is filled, but it is filled with empty lines. If I choose one, the hidden default value will be filled with a number, but the default value for the empty space name is emptying my text. What am I missing?
EDIT: Updated the question with new information based on answers that partially resolved the original issue.
source to share
The simplest solution is probably to customize the JSON. jQueryUI expects data to be marked as
[
{
"id": 2,
"label": "Test Company"
},
{
"id": 3,
"label": "2nd Test Company"
}
]
Then change the method select()
:
select: function (event, ui) {
$('#defaultcompanyid').val(ui.item.id);
$('#defaultcompanyname').val(ui.item.label);
}
If you can't change the JSON try manipulating the method _renderItem()
, take a look at the sample source code in the docs .
Edit: look at the fiddle
source to share