Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Simple Content Search with javascript Re: Simple Content Search with javascript

#103517
Mottie
Member

Hi dynamyc!

The way the plugin is currently written, you won’t be able to extract out the title attribute from the search item. For example, if you had these settings:

'searchList' : 'jThumbnailScroller a',
'searchItem' : 'img'

it would work if “img” was actually an element that contained html, but img tags do not.

So, I ended up making a few changes, I hope you don’t mind, and added a new option named “within”. So now you can initial the plugin like this:

$(function(){
$('.searchFilter').simpleContentSearch({
'hover' : 'searchBoxHover',
'active' : 'searchBoxActive',
'normal' : 'searchBoxNormal',
'searchList' : '.jThumbnailScroller a',
'searchItem' : 'img',
'within' : 'title' // 'html' or any attribute of searchItem
});
});

Here are both of your demos updated: text search & image title search

And the modified plugin code:

$.fn.simpleContentSearch = function ( opts ) {

/**
* Plugin Top Level Scope Variables
*
*/

var settings = {
'active' : 'active',
'normal' : 'normal',
'searchList' : '.searchable tr', // use jQuery selector
'searchItem' : 'td',
'effect' : 'none', // fade, none
'within' : 'html' // html or attribute name
};

var base = this,
options = $.extend({}, settings, opts);

/**
* The main searching method.
* Using the input of the user, search for (base.text())
*/

function startSearching(query, options) {
var elem, str, regexp = new RegExp(query, 'i');
$( options.searchList ).each(function() {
$(this).find( options.searchItem ).each(function() {
elem = $(this);

if (options.within === 'html') {
str = elem.html();
} else {
str = elem.attr(options.within) || '';
}

if (regexp.test(str)) {
elem.closest( options.searchList )[ options.effect === 'fade' ? 'fadeIn' : 'show' ]();
} else {
elem.closest( options.searchList )[ options.effect === 'fade' ? 'fadeOut' : 'hide' ]();
}

});
});
}

return this.each(function() {

// On Blur
base.blur(function(){
base.removeClass(options.active).addClass(options.normal);
});

// On Focus
base.focus(function(){
base.removeClass(options.normal).addClass(options.active);
});

//Keyup
base.keyup(function(){
startSearching(base.val(), options);
});

return this;

});
};

Oh, and please note that the “searchList” option changed to include the “.” needed in the jQuery selector. It’s just better practice to keep it in the option in case you target an ID or element first instead of a class name.