0

Problem Statement: Using javascript or Jquery, I want to build this functionality where if user types a specified character in a textbox, say @ symbol, then values of an array should be displayed in drop down. say for example I have array with values: values[ yyyy,yy]

when User types: abc@ then after @ yyyy and yy should appear in drop down. It is like when we write @ symbol in whatsapp group it shows the list of contacts of that group. this functionality is similar to that. Also, it is different from normal autosuggest which shows suggestions when user types something.It is different from jquery autocomplete functionality, where suggestion is shown based on the input present in the text box. Here we want values of a predefined list in drop down, the moment a user types @ symbol and not on the basis of whole input in the textbox.

Experts please help to achieve this.

R Ram
  • 165
  • 1
  • 3
  • 14

1 Answers1

3

Basic Implementation: You can attach a listener on the keypress in the input / some specific element (Could also be a contenteditable div) and then you can check if the user has pressed the @ key or not.

let element = document.getElementById('#some-element');

element.addEventListener('keydown', function(event) {
  const key = event.key;
  if (key === '@') {
    displaySuggestions();
  }
});

As soon as the user presses the '@' key, you can call the displaySuggestions() functions. It'll be a simple component which you can build and when the user clicks on any of the value in the suggestion, you can insert that value at the caret position.

Refer the following: Insert text into textarea at cursor position (Javascript)

There are many libraries out there which nicely provide this functionality, you may want to check them out.


Update:

I made a small project on codesandbox and you can click on the following link to check it out:

Edit r79o38y75o

This will help with a starting point.

I have documented the code explaining the behavior and how it's being done. In the example I have used a contenteditable div and definitely the example is not optimized for performance but a lot of things can be done around it to improve it.

I agree there are tons of bugs and all of these can be sorted out but in 20-30 minutes, that's all I could do.

To sum it up: You can take inspiration from this or continue editing this or come up with a better solution of yours. Other people might be having great solutions to this and I look forward to them. May the Power of Javascript be with you.

Here's the project in action:

Suggestions Component

Sivcan Singh
  • 1,775
  • 11
  • 15
  • But how can i make a function which displays drop down values when some event is fired in textbox. How this displaysuggestions() function would be built. – R Ram Sep 20 '18 at 21:18