How can I create an editable dropdownlist in HTML?

2019-01-07 10:08发布

I'd like to create a text field with a dropdown list that lets the user choose some predefined values. The user should also be able to type a new value or select a predefined one from a dropdown list. I know that I can use two widgets for that but in my app it would be more ergonomnic if it was unified in a one widget.

Is there a standard widget or do I have to use a third party javascript?

How about browser portability?

9条回答
【Aperson】
2楼-- · 2019-01-07 10:34

You can accomplish this by using the <datalist> tag in HTML5.

<input type="text" name="product" list="productName"/>
<datalist id="productName">
    <option value="Pen">Pen</option>
    <option value="Pencil">Pencil</option>
    <option value="Paper">Paper</option>
</datalist>

If you double click on the input text in the browser a list with the defined option will appear.

查看更多
Fickle 薄情
3楼-- · 2019-01-07 10:40

The <select> tag only allows the use of predefined entries. The typical solution to your problem is to have one entry labeled 'Other' and a disabled edit field (<input type="text"). Add some JavaScript to enable the edit field only when 'Other' is selected.

It may be possible to somehow create a dropdown that allows direct editing, but IMO that is not worth the effort. If it was, Amazon, Google or Microsoft would be doing it ;-) Just get the job done with the least complicated solution. It as faster (your boss may like that) and usually easier to maintain (you may like that).

查看更多
神经病院院长
4楼-- · 2019-01-07 10:40

A combobox is unfortunately something that was left out of the HTML specifications.

The only way to manage it, rather unfortunately, is to roll your own or use a pre-built one. This one looks quite simple. I use this one for an open-source app although unfortunately you have to pay for commercial usage.

查看更多
登录 后发表回答