Rails Against The Machine

Just a mind dump. Why are you even reading this?

Friday, 7 March 2008

 

Local search with Jquery

If you want local live search such as this example it turns out its pretty easy to do with jquery where as the prototype code is pretty horrific. Javascript is as follows

$(document).ready(function(){
$('input#query_string').search();
});

$.fn.search = function() {

$(this).keyup(function(){
var searchString = $(this).val();
var searchElements = "#"+this.getAttribute("search_elements")+"> *";

if (searchString.length > 1){
$(searchElements).hide();
$(searchElements+QueryString(searchString) ).show();
}
else {
$(searchElements).show();
}
});
};

//Extend JQuery by defining Case insensitive search for containing text
jQuery.extend(jQuery.expr[':'], {
Contains :
"jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase())>=0"
});

//Split the query string so that words separated by spaces
//then put this into a single query string
function QueryString(srch)
{
srch=srch.split(/\s+/);
query="";
for (i in srch){
query=query+':Contains(' +srch[i] + ')' ;
}
return query;
}


To use you need a text box such as
<%= text_field_tag :query_string , @query_string,{:search_elements=>'search_results'} %>

the items to filter on the basis of the query_string are all child divs of the div specified by 'search elements'

  <div id="search_results">
<div>
some item to filter
<div>sub divs are also searched</div>
</div>
<div>
some other item to filter
</div>
</div>

Comments: Post a Comment

Subscribe to Post Comments [Atom]





<< Home

Archives

July 2007   August 2007   September 2007   December 2007   January 2008   February 2008   March 2008   April 2008   June 2008   July 2008   August 2008   October 2008   November 2008   January 2009  

This page is powered by Blogger. Isn't yours?

Subscribe to Comments [Atom]