views:

69

answers:

3

Hey guys,

i have a list of items containig names. then i have a eventlistener, which ckecks for keypress event. if the user types i.g. an A all names starting with an A should be viewed with the A bold. so all starting As should be bold.

what is the best way using jquery to highlite only a part of a string?

thanks for your help

A: 

There are jQuery plugins to do text highlighting, but I've not seen one that highlights parts of words.

One possible solution would be to put all your names on the page with the first letter surrounded by a <span> tag, with a class:

<span class='A FL'>A</span>ugustine
<span class='C FL'>C</span>arlos

You can then use jQuery to fiddle with those by class name.

$('whatever').keypress(function(ev) {
  var k = e.which.toUpperCase();
  $('#textContainer span.FL').css('font-weight', 'normal');
  $('#textContainer span.' + k).css('font-weight', 'bold');
});

Note that bold characters are fatter than normal characters, so this is going to have a "wiggly" effect that your users might not like. You might consider changing color instead.

Pointy
hmm .. i thought about that. in this way i have to put spans arround every sign. i'm actually going to expand it to matching strings.if you write "carl" CARLos should be highlited ... not easy, isn't it?
helle
Well if you want to do that, then yes you'll need something different. Here is some code to start with: http://johannburkard.de/blog/programming/javascript/highlight-javascript-text-higlighting-jquery-plugin.html
Pointy
A: 

Here's a function you can call during your keypress event to highlight a search string:

function Highlight(search)
{
    $('ul > li').each(function() {
        if (this.innerHTML.indexOf(search) > -1)
        {
            var text = $(this).text();
            text = text.replace(search, "<span id='highlight' style='font-weight: bold'>" + search + "</span>");
            $(this).html(text);
        }
        else
        {
            this.innerHTML = $(this).text();
        }
    });
}

Test html:

<ul id='list'>
    <li>Bob Jones</li>
    <li>Red Smith</li>
    <li>Chris Edwards</li>
</ul>

It's not quite as elegant as Pointy's answer, but it handles the matching strings requirement.

rosscj2533
A: 

thanks for your help... i figured it out and the detailed resolution comes here:

    var communities = $('#mylist').find('.name');
    var temp_exp = new RegExp("^("+match_string+")","i");
    communities.each(function(i){
        var current = $(this);
        var name = current.text();
        name = name.replace(temp_exp, '<b>$1</b>');
        current.html(name);
    });

while all items have to have the class "name".

helle