0

I have an app where the user types a word and an autocomplete appears. When the select the appropriate autocomplete, it's added to the input field and the user keeps typing. I would very much like to highlight that word in the input box (not in the autocomplete list) and have the rest of the words in the box not appear highlighted, but I can't find any examples of this.

$(searchBoxId).autocomplete({
    source:      keys,
    delay:       0,
    selectFirst: true,
    select:      function(event, ui) {
        var TABKEY = 9;
        this.value = ui.item.value;

        if (event.keyCode == TABKEY) {
            event.preventDefault();
            this.value = this.value + " ";
            // XXX something goes here?
            this.focus();
        }

        return false;
    },
    autoFocus: true,
    minLength: 2
});

This is jquery 1.8.20. By "highlight", I mean "able to make it look visually distinct in a manner similar to how Facebook or Google+ can highlight usernames".

Ovid
  • 11,580
  • 9
  • 46
  • 76
  • possible duplicate of [jQuery wrap selected text in a textarea](http://stackoverflow.com/questions/1712417/jquery-wrap-selected-text-in-a-textarea) – Mark Schultheiss Jun 19 '12 at 13:26
  • or possibly http://stackoverflow.com/questions/646611/programmatically-selecting-partial-text-in-an-input-field – Mark Schultheiss Jun 19 '12 at 13:28
  • Mark, neither is a duplicate, unfortunately. The first embeds the raw HTML in the input field and the second selects text in an input field. Thanks for the pointers, though. – Ovid Jun 19 '12 at 14:21
  • I do not think you will find any other way than those two options for this. Another "option" would be to layer a div over the text input and highlight that way with wraps around the text you want highlighted, but that is not what you asked for. – Mark Schultheiss Jun 19 '12 at 19:20

1 Answers1

1

Since you're already using jQuery, you might want to look at using something like jQuery Tags.

It supports autocomplete and does the data-differentiation you're looking for.

The basic concept is though that you take your text box and make it a div with the contenteditable flag set. Listen for keypress events -- specifically the space bar and the enter key. When they're hit, you grab the most recently entered text (that already isn't "tagged") and create a <div> and append it.

Or just use the plugin...

tkone
  • 22,092
  • 5
  • 54
  • 78