Progressive filtering using jQuery
Here is a simple plugin to filter a result set using jQuery
You "attach" the plugin to a text field and then as you type in that field only the matching records are shown
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="jprogressive.js"></script>
<script type="text/javascript" src="dumpObject.js"></script>
<style>
.jp{display:none;}
</style>
<script language="JavaScript">
<cfparam name="url.startsWith" default="true">
$(document).ready(function(){
$(".jp").hide(); //hide all records first
//attach the plugin to text field myinput
$("#myinput").jprogressive({attribute:"value",dataclass:"jp",startsWith:<cfoutput>#lcase(url.startsWith)#</cfoutput>});
// has nothing to do with plugin we just want to see which words user has selected
$("#mySelect").bind("click",function(){
foo=[];
$(".jp >:checked").each(function(){
foo.push(this.value);
});
alert(foo);
});
})
</script>
<body>
<!-- Just getting some words to choose from -->
<cfquery name="q"datasource="cryptogram" maxrows="500">
Select word from tbl_dictionary
where id%10=0
</cfquery>
<input type="button" value="Select" id="mySelect">
<input type="text" id="myinput"> <!-- this is where we type our filter criteria
<!-- Notice that we give all the divs a common class-->
<cfoutput query="q">
<div class="jp" value="#q.word#">#q.word#<input type="checkbox" value="#q.word#"></div>
</cfoutput>
</body>
</html>
Here is the plugin
$.fn.extend({
jprogressive:function(_options){
var options={};
var config={
attribute:"value",
dataclass:"jprogressive",
startsWith:true
};
//entry point
options=$.extend(options,config);
options=$.extend(options,_options);
return this.each(function(){
$(this).bind("keyup",function(){
$("." + options.dataclass).hide(); //hide everything and then show matches
if ($(this).val() != "") {
if (options.startsWith) {
$("." + options.dataclass + "[" + options.attribute + "^=" + $(this).val() + "]").show();
}
else {
$("." + options.dataclass + "[" + options.attribute + "*=" + $(this).val() + "]").show();
}
}
});
});
}
})
})(jQuery);
The query has three options:
- attribute: The attribute we look for in the displayed elements. The default is "value" It could be "name" or whatever else you choose
- dataclass: This is the class which characterises all your display elements. In our example we use "jp"
- startsWith: if true we look for elements whose attribute value "starts with" the filter, else the value "contains" the filter
Feel free to copy and use the above snippets. There is no error checking etc but you may find it useful.
Try it here
