Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

javascript - How to add multiple values in input field

I am trying to add multiple names from the autocomplete drop-down to the input field like in the image below.

enter image description here

Here’s what I want to build:

  1. When I click on any item from the drop-down, it would add the item in the input field exactly how it is shown in the image.
  2. When I hit backspace in the input field, the entire name should be removed at once.
  3. I can add multiple names and send them to sit in the input field

So basically the name should sit inside that box and that box should sit inside the input field. How do I achieve that in Javascript? I tried searching the web for this but I am not sure if I am putting the right keyword for it. I don’t know what it is called.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

One way to do it is:

<div>
  <div role="button">Eight</div>
  <input />
</div>

You have a container, inside of the container you dynamically insert the selected options first (the inner divs) and then render an input which takes the rest of the space. Also you should render a Menu which handles the list for you.

  1. You do it using javascript. You should know which value has been clicked on add add an element inside your container. (You can use a function to get the label of the options)

  2. One way is to use listen to the key events in your input and ... .

  3. I think if you render other options outside of the input would be better (and easier).

I suggest to take a look at material-ui Autocomplete and inspect it using your browser or if you like take a look at the code in the github. (Or other libraries which have already implemented this)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...