0

i would build a page with Bootstrap and i would use the navbar-search form for find the searched text in the same page. What JS script i should use for do this? I would that for every found text in the page the script add class "lead" to the p tag like this

    <p class="lead">...</p>

How i can do this? Thanks.

Ganjalf
  • 140
  • 1
  • 3
  • 7
  • 2
    Can you clarify the question? You want the user to type in the navbar-search form, and you want the JS script to add the "lead" class to every `

    ` element that contains a match for the search string?

    – LarsH May 23 '13 at 15:27
  • yes, for every found element on this page i would add the class lead to the

    tag

    – Ganjalf May 23 '13 at 15:48

1 Answers1

5

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

MMM
  • 7,221
  • 2
  • 24
  • 42
  • +1, good solution. However you don't have to expect people to search for something "silly" in order to need to escape your regexp substring. If anyone searches for "U.S." or "[1" or "$4" or possibly "(a", they could get errors or wrong results. See http://stackoverflow.com/a/5664273/423105 on how to escape the string. – LarsH May 23 '13 at 18:36
  • @LarsH: Thanks, I agree that the string should be escaped regardless, but I didn't want to complicate the example. – MMM May 23 '13 at 21:29