I am having to use jQuery I did not write, it was included in a template.
There is a function that does a ‘guess type,’ and uses the main navigation as the data to search against. As you type, pages within the site come up in the dropdown.
I need customer names from a database to dropdown, but I can’t seem to get the function to work.
function searchInNav(s)
{
// Split keywords
var keywords = s.toLowerCase().split(/\s+/);
var nbKeywords = keywords.length;
// Search links
//var links = $('nav a'); // original
var links = [];
// LOAD CUSTOMERS AND EVENTS
$.post('includes/ajax/global.php', { list: 'search', text: keywords },
function(data){
alert(data);
links.push($(data));
},
"html"
);
var matches = [];
links.each(function(i)
{
var text = $(this).text().toLowerCase();
var textMatch = true;
for (var i = 0; i < nbKeywords; ++i)
{
if (text.indexOf(keywords[i]) == -1)
{
textMatch = false;
break;
}
}
if (textMatch)
{
// All keywords found
matches.push(this);
}
});
// Build results list
var nbMatches = matches.length;
if (nbMatches > 0)
{
var output = '<p class="results-count"><strong>'+nbMatches+'</strong> match'+((nbMatches > 1) ? 'es' : '')+'</p>';
output += '<ul class="small-files-list icon-html">';
for (var m = 0; m < nbMatches; ++m)
{
// Text with highlighted keywords
var link = $(matches[m]);
var text = link.text();
var path = [text];
for (var i = 0; i < nbKeywords; ++i)
{
text = text.replace(new RegExp('('+keywords[i]+')', 'gi'), '<strong>$1</strong>');
}
// Path
var parent = link;
while ((parent = parent.parent().parent().prev('a')) && parent.length > 0)
{
path.push(parent.text());
}
output += '<li><a href="'+matches[m].href+'">'+text+'<br><small>'+path.reverse().join(' > ')+'</small></a></li>';
}
return output+'</ul>';
}
else
{
return '<p class="results-count">'+settings.messageNoMatches+'</p>';
}
};
I keep getting errors with the links.each line, saying Object has not method each.
What do I need to fix?
Thanks!
This is your problem:
$(‘nav a’) makes a jQuery object of all a tags in nav. yours is just an array.
You need to modify that whole loop to handle it as an array and not a jquery object…
But I can’t guearntee this modification above. The general concept is that you changed it from a jquery object to an array so you have to modify the loop accordingly.
Also, what is this:
Is data returning an expected dom id? like #some_div? Otherwise that $() makes no sense. It should just be data.