6

I'd like to know how to highlight some text within an input box; simple example, let's say I want to highlight all the terms starting by "@" while typing.

All the terms are retrieved from a remote autocomplete suggestions list.

The problem I'm facing is this input box, because I can't add html tags around the text and therefore can't make css on those specific terms...

Thanks for your help !

Cheers!

2
  • 1
    You need to look at contentEditable, making an editable area for your input, will allow you to highlight the text in the way you describe. Alternatively you could use tinyMCE, but between the two contentEditable and editable divs will be the easier to learn how to use. Commented Aug 26, 2012 at 10:44
  • I Googled it in all possible queries, even looked how Stackoverflow did its tag selection when posting a question, but honestly, I can't figure out how to only highlight the term that has been retrieved (they alls start by "@"). It's actually similar to FB functionality when you type "@[username]", the value is highlighted once selected. Commented Aug 26, 2012 at 10:49

2 Answers 2

5

You can use .select method in jQuery... Here is a simple example.

$(input).focus(function() { this.select(); }); 

OR

$('input').click(function() { // the select() function on the DOM element will do what you want this.select(); }); 

FIDDLE DEMO

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for your answer @Vins, but it's not because it's selected that I can highlight it afterwards, right?
I think you misunderstood the question, 'highlight' has sort of 2 meanings.
The .select() is not a jQuery method, rather it's native JavaScript. The proof is in your example. this within your jQuery callback handler is the event.target object, which is nothing more than a vanilla DOM element object. Here, the target is an input element that was clicked. this.select() is a a DOM API method , not a jQuery function.
4

This, I hope, is what your after.

First take a look at highlightTextarea. Made by Julien L

With this you can do the following:

$("textarea").highlightTextarea({ words: ["\\B@\\w+"], color: "lightblue", id: "mark" }); 

The regex \\B@\\w+ assert position at an non word boundary (\B), followed by a @ and matches everything that falls under \w.

DEMO

5 Comments

Perhaps add [ \t] before the '@', or else words that CONTAIN an '@' will be half highlighted!
@11684 I guess you mean \s and not \t? \t is a tab character.
Works for me as a space, see my answer!
+1! great answer! Could you look at mine? Do you see what goes wrong?
404 on DEMO link

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.