JQuery Search Suggester Plugin
While writing a simple knowledgebase application for my web company I wanted to create the facility to automatically suggest articles as the user typed in a question.
So I came up with the following ‘suggester’ plugin. To get it working, you need to:
- Attach it to an input field
- Pass in the backend URL to load via AJAX
- Supply a callback function called results_cb where the data gets sent.
Typically your results_cb function will be responsible for displaying the returned options to the user.
Your backend script needs to respond to the POST variable unimaginatively named ‘search’.
The plugin doesn’t impose any ideas about what sort of data you’re receiving back, or how to display it, but this makes it more flexible and resusable in my opinion.
Here’s an example of how it can be used:
$('input').suggester(
{ url : 'search.php',
results_cb : function(data) { alert(data); },
mode : 'text'}
)
And here’s the plugin itself:
/**
* JQuery suggester plugin 0.1
* J A Carmichael
* www.siteclick.co.cuk
*
* License: MIT
*
* If you use this, please consider linking to www.siteclick.co.uk :)
*
* 12/5/2009
* attach this to a field, eg $(input).suggester()
* options:
* url : The URL to call with the search term
* results_cb : A callback to call when data is loaded via AJAX
* mode : the type of data to send to the callback - default JSON
*/
jQuery.fn.suggester = function(settings) {
// Set defaults
var settings = jQuery.extend({
'url' : '',
'results_cb' : function() {},
'on_search' : function() {},
'mode' : 'json'
}, settings);
// For each item
return this.each(function(){
// The field which the user is typing in
var inputField = this;
// A flag to indicate whether typing currently
var typing = false;
// Current search term
var searchTerm = '';
// The last search
var currentSearch = '';
/**
* Function to do the searching every so often
*/
var searchFunc = function() {
if(!typing && (searchTerm != currentSearch)) {
currentSearch = searchTerm;
// Call the function to indicate we're now searching
settings.on_search(searchTerm);
// Send post request
$.post(settings.url, 'search=' + encodeURIComponent(searchTerm), settings.results_cb, settings.mode);
}
// Keep calling the search function
window.setTimeout(searchFunc, 500);
}
/**
* Handler for when a key is depressed on this field
*/
jQuery(inputField).keyup(function() {
typing = true;
// Update the search term
searchTerm = $(this).val();
// Reset the typing flag after a certain time
window.setTimeout(function() {
typing = false;
}, 500);
})
// Start searching
searchFunc();
})
}
Leave a comment