logo

jQuery Search Content

Add comment

In this tutorial I’ll show you how you can create jQuery plugin that will search for some words in tables and display those rows that have entered words in their cells.

Folders And Files Top

On image below you can see folders and files we will use. It’s nothing to complicated.

jQuery Search Folder Structure

jQuery Search Folder Structure

We have folders for our stylesheets, images and javascript files. In jQuery is jQuery main file. Files main.js and search.js are for our plugin as you’ll see later. index.php is our main file.

Main.css And Index.php Codes Top

Since I do not intend to explain your CSS and HTML I’ll just paste those codes here since they are very simple.

main.css

@CHARSET "UTF-8";

body {
    background-color: #e8eef1;
}

#wrapper {
	width: 700px;
	margin: 40px auto;
}

#searchBoxWrapper {
	width: 217px;
	height: 28px;
	margin: 0px auto;
}

#searchBox {
	border: none;
	width: 207px;
    height: 14px;
    padding: 8px 5px;
    color: #5c9bba;
}

#searchBox.searchBoxNormal {
	background: url('../img/boxes.png') no-repeat top left;
}

#searchBox.searchBoxHover {
    background: url('../img/boxes.png') no-repeat left -30px;
}

#searchBox.searchBoxActive {
    background: url('../img/boxes.png') no-repeat left -60px;
    color: #000;
}

#exampTable {
	color: #186e98;
	width: 200px;
	border: none;
	margin: 0px auto;
	margin-top: 30px;
}

#exampTable tr {
	width: 50%;
}

index.php

< !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>jQuery search</title>
        <link href="css/main.css" type="text/css" media="screen, projection" rel="stylesheet" />
    </head>

    <body>
        <div id="wrapper">
            <div id="searchBoxWrapper">
                <input type="text" name="searchBox" id="searchBox" class="searchBoxNormal" />
            </div>
                <table id="exampTable">
                    <tbody>
                        <tr>
                            <td>Apples</td>
                            <td>44%</td>
                        </tr>
                        <tr>
                            <td>Bananas</td>
                            <td>23%</td>

                        </tr>
                        <tr>
                            <td>Oranges</td>
                            <td>13%</td>
                        </tr>
                        <tr>
                            <td>Other</td>

                            <td>10%</td>
                        </tr>
                </tbody>
            </table>
        </div>
        <script type="text/javascript" src="js/jquery/jquery-1.3.2.js"></script>
        <script type="text/javascript" src="js/search.js"></script>
        <script type="text/javascript" src="js/main.js"></script>
    </body>
</html>

As you can see, in HTML code we have one table with four fruits and some numbers. That we will use as our data that we will search in. You can also see that we have some input element and we will write our words in it

Plugin Start Top

Now we can start building our plugin. First we have to do is to place in our search.js file block of code that will tell jQuery that it’s for him. We do this by writing an anonymous function that takes $ as an argument and on the and we add (jQuery).

(function($)
{
	// Here will go our plugin's code
})(jQuery);

Now we can go further. Next thing we need to do is to tell jQuery that he has a new plugin. We do this by placing our plugins function in jQueries registry of functions like this. We want that our plugin can take some options and that’s why we add opt as argument. You can have as many as you wish, but we need just one.

$.fn.extend({
	'searchBox'	: function(opt) {
		// This is main function of our plugin
	}

});

When you did this, your plugin is available to be called as a function like this.

$('#someId').searchBox({});

After that we will create one variable that will have default options. Place this code after searchBox part.

$.searchBox = function () {};

$.searchBox.defaults = {
	'hover'		: 'hover',
	'active'	: 'active',
	'normal'	: 'normal',
	'text'		: 'Search for ...'
};

We set some default values that user can choose.

Now we need two extra function. First function, addText(elem, opt), will add text to our search box and second, searchForIt(query), will search our page for query entered in search box.

addText(elem, opt) Top

function addText(elem, opt)
{
	elem = $(elem);

	if (elem.val() === '')
		elem.val(opt.text);
}

This function is very simple. It only writes text to elements value attribute.

searchForIt(query) Top

function searchForIt(query)
{
	$('#exampTable tr').each(function ()
	{
		$(this).children('td').each(function ()
		{
			var elem = $(this);

			//console.log(val.match(/.*?a.*?/i));

			if (!elem.html().match(new RegExp('.*?' + query + '.*?', 'i'))) {
				$(this).parent('tr').css('display', 'none');
				//console.log(query);
			} else {
				$(this).parent('tr').css('display', '');
				return false;
			}

			return ;
		});
	});
}

This function goes through each td element in our table and checks if it contains search text. If it does not contain it, it hides parent tr element.

Now we can build our main function.

Main Function Top

First we have to takes options that someone choose and extend it with our default (those that are missing should be added).

var opt = $.extend({}, $.searchBox.defaults, opt);

Then we’ll call our function addText() and create flag that will tell us if user is typing or not.

addText(this, opt);

var click = false;

Then we’ll create some event listeners. First event listener will take care of CSS and it will have two anonymous functions. First function will be called when user hovers and second when user removes mouse from element but only if he hasn’t already clicked on it.

$(this).hover(function ()
{
	if (!click)
		$(this).removeClass().addClass(opt.hover);
}, function ()
{
	if (!click)
		$(this).removeClass().addClass(opt.normal);
});

Next we’ll have event listener for blur action. This will reset input box to it’s default state if user hasn’t typed something in it.

$(this).blur(function ()
{
	var elem = $(this);

	if (elem.val() === '' || elem.val() === opt.text) {
		elem.removeClass().addClass(opt.normal);
		addText(this, opt);
		click = false;
	}
});

Event listener for focus will add focus class and set flag to true.

$(this).focus(function ()
{
	var elem = $(this);

	elem.removeClass().addClass(opt.active);

	if (elem.val() === opt.text)
		elem.val('');

	click = true;

});

And lest event listener will be triggered when user press some key on keyboard. It only calls searchForIt() function.

$(this).keyup(function ()
{
	searchForIt($(this).val());
});

Conclusion Top

Now is our jQuery search tutorail is finished and you know how to create it by yourself. You can also download source code from here or try live version here. Thank you for reading.

Related Posts
  • 22.10.2009 — jQuery Basic Tutorial (0)
    User named Enrho requested a tutorial that will explain some basics in jQuery. This will be a very s…
  • 30.12.2009 — Ext JS 3.0 Cookbook (3)
    As I announced before, I’ve got a promo version of a book Ext JS 3.0 Cookbook from PacktPub. I final…
  • 23.12.2009 — Learning Resources (0)
    Reader Satish requested a list of tutorials where he could learn about PHP, MySQL and jQuery. Since …
  • 04.12.2009 — Ext JS 3.0 Cookbook Announced (0)
    A few days ago, I’ve got an e-mail from PacktPub in which I’ve been asked to make a review about Ext…
  • 09.09.2009 — AJAX Multi-Level Comments (16)
    In this tutorial we will create multi level comments. You must have seen comments on youtube and tha…
  • 29.06.2009 — jQuery AJAX tutorial (46)
    This tutorial cover some of basics about jQuery and AJAX. We will build AJAX form submit where we wi…
  • 16.10.2009 — PHP DomDocument Tutorial (5)
    This will be a quick tutorial that will show you how to use PHP’s DOMDocument to parse your XML so y…

logo

2 comments to “jQuery Search Content”

  1. nadeem says:

    Goood one contact me nadeem.qaisar@gmail.com

  2. green eye girl :) says:

    i don’t understand you, but i like you :D
    sendinig you a big hug & kiss :)

    *i was here xD

Leave a Reply


 *


 *


logo
logo
Powered by Wordpress | Designed by Elegant Themes | CopyRight ©2010 php4every1.com