Twitter-style autocomplete in textarea

前端 未结 10 1124
情歌与酒
情歌与酒 2020-12-02 06:38

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

  • Can be used in a HTML textarea
  • Allows for typing regular text
相关标签:
10条回答
  • 2020-12-02 07:12

    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.

    Edit
    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.

    0 讨论(0)
  • 2020-12-02 07:15

    THIS should work. With regards to the @ kicking off the search, just add (dynamically or not) the symbol to the beginning of each possible search term.

    0 讨论(0)
  • 2020-12-02 07:16

    Recently i had to face this problem and this is how i nailed down...

    1. Get the string index at the cursor position in the textarea by using selectionStart
    2. slice the string from index 0 to the cursor position
    3. Insert it into a span (since span has multiple border boxes)
    4. Get the dimensions of the border box using element.getClientRects() relative to the view port. (here is the MDN Reference)
    5. Calculate the top and left and feed it to the dropdown

    This works in all latest browsers. haven't tested at old ones

    Here is Working bin

    0 讨论(0)
  • 2020-12-02 07:17

    This small extension seems to be the closest at least in presentation to what was asked. Since it's small, it can be easily understood and modified. http://lookapanda.github.io/jquery-hashtags/

    0 讨论(0)
提交回复
热议问题