“Search Auto Suggestion”, like Google

December 27th, 2011

I was recently playing around with some code to make an “auto suggest” function for when people do searches / add values into an input field. Here is what I came up with:

View the example

Its pretty simple to setup:

1) Add in the jQuery library (if you don’t already have it!):

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>

2) Add the following Javascript code into your page:

	jQuery.noConflict();
	jQuery(document).ready(function() {
		jQuery('#searchbox').attr("autocomplete", "off");

		jQuery('#searchbox').keyup( function() {
			inputString = jQuery(this).val();
	        if(inputString.length < 2) {
				jQuery('#suggestions').fadeOut();
	        } else {
				jQuery('#searchbox').addClass('load');

				jQuery.post("/cgi-bin/suggest.cgi", { query: escape(inputString) }, function(data) {
					if(data.length > 0) {
						jQuery('#suggest').fadeIn();
						jQuery('#suggestions').fadeIn();
						jQuery('#suggestionsList').html(data);
						jQuery('#searchbox').removeClass('load');
					}
				});

	        }
	    });

		jQuery('#suggest').mouseleave( function() {
			jQuery('#suggest').fadeOut();
		});

	});

	function fill(thisValue) {
		jQuery('#searchbox').val(thisValue);
		setTimeout("jQuery('#suggestions').fadeOut();", 200);
		jQuery('#searchform').submit();
	}

3) Add the following CSS:

#suggest {
	position:relative;
}
.suggestionsBox {
	margin-left: 0px;
	display: none;
	position:absolute;
	z-index: 100;
	width: 200px;
	padding:0px;
	background-color: #7A7476;
	border-top: 3px solid #000;
	color: #fff;
}

.suggestionList {
	margin: 0px;
	padding: 0px;
}
.suggestionList ul li {
	list-style:none;
	margin: 0px;
	padding: 6px;
	border-bottom: 1px dotted #666;
	cursor: pointer;
}
.suggestionList ul li:hover {
	background-color: #FC3;
	color:#000;
}
#suggest ul {
	font-family: Arial, Helvetica, sans-serif;
	font-size:11px;
	color:#FFF;
	padding:0;
	margin:0;
}

.load{
	background-image:url(/examples/autosuggest/suggest_loader.gif);
	background-position:right;
	background-repeat:no-repeat;
}

To make it align correctly to your input, you will probably need to play around with the bit highlighted (line 5), so that it correctly indents from the left margin.

4) Download the following files and upload them into your chosen directory.

5) CHMOD the suggest.cgi script to 755, and then open it up in your prefered editors (NotePad++, NotePad, WordPad, etc) … then edit the following values:

	my $database = "database_name";
	my $host = "localhost";
	my $port = "3306";
	my $user = "yourusername";
	my $pass = "the_db_password";
	my $debug = 0;

6) Run the following mySQL query in your database, to add create the table and also add in a couple of test entries:

CREATE TABLE IF NOT EXISTS `Suggestions` (
  `suggestion_id` int(11) NOT NULL AUTO_INCREMENT,
  `suggestion_query` varchar(255) NOT NULL,
  PRIMARY KEY (`suggestion_id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;

INSERT INTO `Suggestions` (`suggestion_id`, `suggestion_query`) VALUES
(1, 'testing'),
(2, 'testing more'),
(3, 'testing something else');

7) The final part is to add in the HTML for where the suggestions will show up:

	<input id="searchbox" type="text" name="s" />
	<div id="suggest">
		<div class="suggestionsBox" id="suggestions" style="display: none;">
			<div class="suggestionList" id="suggestionsList"> &nbsp; </div>
		</div>
	</div>

Thats pretty much it. You need to make sure the “loader” image in the CSS is setup correctly (to point to the URL on your site), as well as the line in the JS code, which points to suggest.cgi:

jQuery.post("/cgi-bin/suggest.cgi", { query: escape(inputString) }, function(data) {

Any questions, please ask :)

Andy

Andy

I’ve been working as a Web-Design / Coder for many years now, and thought it was finally time for me to give back some of the stuff I’ve learned over the years. I started this blog in November 2010, and have already added quite a few varying articles to the site. I’m always looking for new suggestions, so please visit the forum, or shoot me an email with suggestions!

WebsiteMore Posts

Categories: jQueryPerl Coding

Related Posts: