Martin Wiboe Martin Wiboe - 1 year ago 209
Javascript Question

Twitter-style autocomplete in textarea

I am looking for a Javascript autocomplete implementation which includes the following:

  • Can be used in a HTML textarea

  • Allows for typing regular text without invoking autocomplete

  • Detects the
    character and starts autocomplete when it is typed

  • Loads list of options through AJAX

I believe that this is similar to what Twitter is doing when tagging in a tweet, but I can't find a nice, reusable implementation.

A solution with jQuery would be perfect.


Answer Source

I could not find any solution that matched my requirements perfectly, so I ended up with the following:

I use the jQuery keypress() event to check for the user pressing the @ character.
If this is the case, a modal dialog is shown using jQuery UI. This dialog contains an autocomplete text field (many options can be used here, but I recommmend jQuery Tokeninput)
When the user selects an option in the dialog, a tag is added to the text field and the dialog is closed.

This is not the most elegant solution, but it works and it does not require extra keypresses compared to my original design.

So basically, we have our large text box where the user can enter text. He should be able to "tag" a user (this just means inserting #<userid> in the text). I attach to the jQuery keyup event and detect the @ character using (e.which == 64) to show a modal with a text field for selecting the users to tag.

The meat of the solution is simply this modal dialog with a jQuery Tokeninput text box. As the user types here, the list of users is loaded through AJAX. See the examples on the website for how to use it properly. When the user closes the dialog, I insert the selected IDs into the large text box.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download