Shaun Mccran

My digital playground

22
D
E
C
2010

Filtering a SELECT field using AJAX and JQuery

I've got a select form field, and I want it to change based on a search string that someone enters. Luckily for me the select field is dynamically driven from a database, so the most obvious way for me to do this is to make an AJAX post request using the string entered to amend the SQL query building the field.

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.

view plain print about
1<select name="locations" id="locations" size="5">
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.

view plain print about
1SELECT [id], [varCode], [varLocation]
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.

view plain print about
1// watcher for the client ref field
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.

view plain print about
1<cffunction name="filterLocations" access="remote" returnformat="json" hint="populates a select field with locations using the text as a filter">
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/

TweetBacks
Comments (Comment Moderation is enabled. Your comment will not appear until approved.)
metal roof's Gravatar so the most obvious way for me to do this is to make an AJAX post request using the string entered to amend the SQL query building the field.
# Posted By metal roof | 14/10/2015 06:24
Personal Injury Attorneys's Gravatar I haven’t any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human....
# Posted By Personal Injury Attorneys | 18/10/2015 05:12
Build My List 2.0 Bonuses's Gravatar .Really i am impressed from this post....the person who create this post it was a great human...
# Posted By Build My List 2.0 Bonuses | 07/11/2015 22:40
click to investigate's Gravatar 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.
# Posted By click to investigate | 13/12/2015 21:40
Xarelto Deaths - Lawsuits's Gravatar I'm able to bookmark your site and show the kids check out up here generally. I m fairly positive there likely to be informed a great deal of new stuff here than anyone.
# Posted By Xarelto Deaths - Lawsuits | 19/12/2015 01:56
dedicated server's Gravatar 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.
# Posted By dedicated server | 19/12/2015 03:01
Medical Training's Gravatar Great Post This is also a very good post which I really enjoyed reading. It is not everyday that I have the possibility to see something like this..Thank You!
# Posted By Medical Training | 21/12/2015 02:06
cheap papers for sale's Gravatar Firstly create a CurrencyFormatter object, and specify the currency symbol, and any other formatting parameters that you require.
# Posted By cheap papers for sale | 26/12/2015 02:02
check this out's Gravatar Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long.
# Posted By check this out | 28/12/2015 01:29
check this out's Gravatar Your site and show the kids check out up here generally. I m fairly positive there likely to be informed a great deal of new stuff here than anyone.
# Posted By check this out | 29/12/2015 00:15
buy a research paper for college cheap's Gravatar Use AJAX convention to send that to a less important PHP file, which uses the data it receives to write several HTML code based on what the consumer decide.
# Posted By buy a research paper for college cheap | 04/01/2016 01:40
pure garcinia cambogia's Gravatar Your site and show the kids check out up here generally. I m fairly positive there likely to be informed a great deal of new stuff here than anyone.
# Posted By pure garcinia cambogia | 07/01/2016 01:15
sell online's Gravatar I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation.
# Posted By sell online | 09/01/2016 00:52
Victorino Noval and Manny Pacquiao's Gravatar I’m not that much of a internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. All the best...
# Posted By Victorino Noval and Manny Pacquiao | 11/01/2016 23:10
monthly subscription boxes for men's Gravatar I’ve been thinking about writing a very comparable post over the last couple of weeks. I’ll probably keep it
# Posted By monthly subscription boxes for men | 12/01/2016 22:05
movers and packers pune's Gravatar internet reader to be honest but your blogs really nice, keep it up! I’ll go ahead and bookmark your site to come back in the future. All the best...
# Posted By movers and packers pune | 13/01/2016 22:21
couples therapy in berkeley's Gravatar So luck to come across your excellent blog. It is filled with interest that let me read relaxing.
# Posted By couples therapy in berkeley | 14/01/2016 00:54
taxi for delhi jaipur's Gravatar Really i am impressed from this post....the person who create this post it was a great human....
# Posted By taxi for delhi jaipur | 14/01/2016 04:09
more's Gravatar I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank youa for the efforts you have made in writing this article.
# Posted By more | 16/01/2016 02:58
Lit enfant's Gravatar Good post but I was wondering if you could write a little more on this subject? I’d be very thankful if you could elaborate a little bit further..
# Posted By Lit enfant | 17/01/2016 23:16
פיתוח רעיון עסקי's Gravatar I'm just seriously able to obtain this blog plus have love looking through handy reports created listed here. A strategies of your article writer appeared to be magnificent, with thanks for any promote.
# Posted By פיתוח רעיון עסקי | 18/01/2016 23:20
פורטל בעלי מקצוע's Gravatar I'm just seriously able to obtain this blog plus have love looking through handy reports created listed here. A strategies of your article writer appeared to be magnificent, with thanks for any promote.
# Posted By פורטל בעלי מקצוע | 19/01/2016 01:19
DUI Lawyer's Gravatar I have feel that this blog is really have all those quality that qualify a blog to be a one.I wanted to leave a little comment to support you and wish you a good continuation.
# Posted By DUI Lawyer | 19/01/2016 23:40
Property Report's Gravatar You share tons of interesting info, neat and excellent design you’ve got here. It’s certainly one of the most informative stuff on this topic I’ve ever read...
# Posted By Property Report | 20/01/2016 22:28
http://brightcab.com/jaipur-to-ajmer-taxi/'s Gravatar 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.
# Posted By http://brightcab.com/jaipur-to-ajmer-taxi/ | 04/02/2016 01:27
delhi to ajmer taxi's Gravatar I've also added the text field below to allow a user to enter a filter string.
# Posted By delhi to ajmer taxi | 04/02/2016 01:28
Back to top