As Bootstrap requires jQuery for its plugins to work, I'll use it for your solution:
If your navbar-search
is a class:
$(".navbar-search").on("keyup", function () {
var v = $(this).val();
$(".lead").removeClass("lead");
$("p").each(function () {
if (v != "" && $(this).text().search(v) != -1) {
$(this).addClass("lead");
}
});
});
Bear in mind that this will not look for words but for characters (so when you start typing say a
, it will select both paragraphs straight away since both of them contain 'a'). If you want to search for words, you need to amend your code accordingly.
This solution is case-sensitive.
JSFiddle
So if you want to search for whole words, do this:
$(".navbar-search").on("keyup", function () {
var v = $(this).val();
$(".lead").removeClass("lead");
var re = new RegExp("\\b" + v + "\\b","g")
$("p").each(function () {
if (v != "" && $(this).text().search(re) != -1) {
$(this).addClass("lead");
}
});
});
Just bear in mind that you might want to escape your v
before inserting it into the regexp if you expect people to search for something silly.
JSFiddle
` element that contains a match for the search string?
– LarsH May 23 '13 at 15:27tag
– Ganjalf May 23 '13 at 15:48