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

Categories

0 votes
729 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 Reply

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...