|
Filtering a SELECT field using AJAX and JQuery |
This article shows you how to do this, there is a demo of the select field using AJAX here: http://www.mccran.co.uk/examples/jquery_textfilter_selectfield/
Firstly create a form with a select field in it. I have populated mine with a query, like this. I've also added the text field below to allow a user to enter a filter string.
2<cfloop query="qGetLocations">
3<option value="#qGetLocations.id#">
4#qGetLocations.varLocation#
5</option>
6 </cfloop>
7</select>
8
9<label for="filterText">
10Filter the select field using this string:
11</label><br>
12<input type="text"
13 name="filterText"
14 id="filterText"
15 size="10"
16 value="">
This is populated from a very simple SQL query.
2FROM dbo.ukLocationCodes
3ORDER BY varLocation
The interesting bit is where someone starts to enter text into the 'filterText' element. I've created a JQuery selector that watches for a keyup event. This then runs a function that makes an AJAX request to a cfc, which delivers a filtered query object back to the page.
2$("#filterText").keyup(getSelectField);
3
4 // function to manage drop down from the filter box
5 function getSelectField() {
6 var thisValue = $(this).attr("value");
7
8 // search on the clients for this number
9 $.post("ajax.cfc?method=filterLocations", { varLocation: thisValue },
10
11 function (data) {
12 jsonResponse = eval( "(" + data + ")" );
13
14 // set the select box
15 var selector = $('#locations');
16
17 // remove the existing options
18 var options = selector.attr('options');
19 $('option', selector).remove();
20
21 // add the new ones
22 $.each(jsonResponse, function(val, text) {
23 options[options.length] = new Option(text, val);
24 });
25 });
26 }
27 //end
This function then removes all the select options, and repopulates it with the returned AJAX query.
The CFC that performs the query is here, note that I'm building a formatted json response myself because this is running on ColdFusion server 7 and 8, so the returnformat value doesn't always work.
2 <cfargument name="varLocation" type="string" required="false" hint="job ref to search on">
3
4 <cfquery datasource="ds" name="qLocations">
5 SELECT [id], [varCode], [varLocation]
6 FROM dbo.ukLocationCodes
7 WHERE varLocation LIKE '%#arguments.varLocation#%'
8 ORDER BY varLocation
9 </cfquery>
10
11 <cfoutput>{<cfloop query="qLocations">"#qLocations.id#" : "#ucase(left(qLocations.varLocation,1))##lcase(right(qLocations.varLocation,len(qLocations.varLocation)-1))#"<cfif qLocations.currentRow LT qLocations.recordcount>,</cfif></cfloop>}</cfoutput>
12 </cffunction>
There is a demo of the select field using AJAX here: http://www.mccran.co.uk/examples/jquery_textfilter_selectfield/