Detect ":" and show suggestions with jQuery

Asked

Viewed 56 times

2

I own a textarea and would like to know how to detect the character : and, from there, show suggestions listed in an array with all the possibilities of "auto complete" and go filtering the results...

Below is an example:

inserir a descrição da imagem aqui

I’ve thought about detecting the character : from the keydown using the event keyCode but I don’t know how I would do since in Windows I would have to detect the shift + : and on Mac I no longer know if it’s the same thing. I also thought of just detecting the character : from the val() of textarea but I don’t know how I could proceed.

What is the right way to do it? And, how to do it?

Preferably, I would really like to learn how to do it only with jQuery and without using libraries.

Thank you!

1 answer

2

There are some libraries out there to make autocomplete inside a textarea. Have you ever thought about using one? For example: https://github.com/yuku-t/jquery-textcomplete

If I’m not mistaken, most of them detect the position of the cursor within the textarea instead of looking at the keycode. One advantage of this is that you can filter the dropdown as you type. The bad news is that browsers don’t have a consistent API to get the cursor position.

  • This would solve my problem, but, I have a doubt, would not be able to do this without using plugins? I would like to learn...

  • You can look at the plugins' source code and see what they do behind the scenes :) I don’t exactly remember the details, only it has Apis that allow you to grab the text right behind the cursor.

  • One way to do it would be to monitor the 'keyup' event and with each shot of this event you search in . val(). strpos(':') if the returned value is different from -1 means that you found ':', so just run your suggestion routine

Browser other questions tagged

You are not signed in. Login or sign up in order to post.