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!

jozi
  • 316
  • 1
  • 2
  • 14
  • 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. – Liam Bailey Aug 26 '12 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. – jozi Aug 26 '12 at 10:49

2 Answers2

4

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

Vins
  • 8,849
  • 4
  • 33
  • 53
  • Thanks for your answer @Vins, but it's not because it's selected that I can highlight it afterwards, right? – jozi Aug 26 '12 at 10:57
  • I think you misunderstood the question, 'highlight' has sort of 2 meanings. – 11684 Aug 26 '12 at 11:32
  • 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](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select) , not a jQuery function. – seebiscuit May 29 '15 at 22:19
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

Community
  • 1
  • 1
sQVe
  • 1,977
  • 12
  • 16