How to use jQuery UI Autocomplete with ColdBox and BootStrap


To add jQuery UI autocomplete functionality in ColdBox, do the following:

  • Reference jQuery UI in the main layout
  • Create a helper function to retrieve the required data
  • Use autocomplete on the view page

Environment

  • ColdBox 3.8
  • BootStrap 3.1.1
  • ColdFusion 10

1 Reference the jQuery UI in the main layout

Open layouts\Main.cfm and add the following reference to the style sheet and JavaScript for jQuery UI (if not already present), i.e.


<head>
  <link href="/path/to/bootstrap/bootstrap.min.css" rel="stylesheet" type="text/css"/ >
  <link href="/path/to/jquery-ui/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
</head>
<body>
  <script src="/path/to/jquery/jquery.11.1.js"></script>
  <script src="/path/to/jquery/ui/jquery-ui.min.js"></script>
  <script src="/path/to/bootstrap/bootstrap.min.js"></script>
</body>

2 Create a helper function to retrieve the required data

Load includes\helpers\ApplicationHelper.cfm and add the following function:


<cffunction name="getUniqueID" access="remote" output="no" returnFormat="json">
  <cfscript>
    var qGet = "";
    var uniqueIDList = [];
  </cfscript>
  <cfquery name="qGet" datasource="<data-source-name>">
    SELECT DISTINCT clientID FROM clients
    ORDER BY clientID
  </cfquery>
  <cfscript>
  //convert query to array
  for (var row in qGet){
    ArrayAppend(uniqueIDList,row.clientID);
  }
  return uniqueIDList;
  </cfscript>
</cffunction>

3 Use jQuery UI Autocomplete on the view page

In the view page, for example, the edit.cfm where autocomplete is needed, add the following code:


<script>
  <cfoutput>var #toScript(getUniqueID(), "idList")#;</cfoutput>
  $(document).ready(function() {
    //ID are retrieved from db
    $( "#clientiD" ).autocomplete({
      source: idList
    });
  });
</script>

Here we use the ColdFusion toScript function to convert ColdFusion value to JavaScript saving it as idList. getUniqueID is the ColdBox helper function which we added to ApplicationHelper.cfm. This variable stores the json formatted array of values which is used as input source for the jQuery UI autocomplete. Also ensure that the target input element has the matching id, in this instance it is clientID, e.g.


<div class="form-group required">
  <label for="clientID" class="col-md-4 control-label">Client</label>
  <div class="col-md-3">
    <input type="text" name="clientID" class="form-control" id="clientID" value="" placeholder="e.g. 1234567">
  </div>
</div>

This is the result when the autocomplete works:

autocomplete-1a

As you can see when you type the digit 6, all values that contains a 6 show up for selection in a drop down list.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.