如何在 HTML 选择标签中输入文本?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15506601/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 06:40:45  来源:igfitidea点击:

How to input text in HTML Select Tag?

htmlhtml-select

提问by user1455966

I want to make input option in select tag so user can choose between options or insert different value.
Is it possible?

我想在选择标签中设置输入选项,以便用户可以在选项之间进行选择或插入不同的值。
是否可以?

<select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
  **<insert user value>**
</select>

回答by Vil

HTML solution with "list" attribute:

具有“列表”属性的 HTML 解决方案:

<input type="text" name="city" list="citynames">
<datalist id="citynames">
  <option value="Boston">
  <option value="Cambridge">
</datalist>

回答by Fencer04

You will have to use javascript to get the additional value. Check this post for some example code:

您将不得不使用 javascript 来获取附加值。查看此帖子以获取一些示例代码:

Jquery dynamically update "other" option in select

Jquery动态更新选择中的“其他”选项

回答by Tracy Fu

Select elements can't contain anything other than optionor optgroupelements. Here's a ref to the spec http://www.w3.org/TR/html5/forms.html#the-select-element

Select 元素不能包含除optionoptgroup元素之外的任何内容。这是对规范http://www.w3.org/TR/html5/forms.html#the-select-element的引用

You may be better off adding an option for "other" in your dropdown and then using JS to detect for that choice to dynamically show an input (below the dropdown) for a custom value.

您最好在下拉列表中为“其他”添加一个选项,然后使用 JS 检测该选项以动态显示自定义值的输入(下拉列表下方)。

回答by Jeff

Position an input box over the select box and remove the border of the input box. Make the length of the input box shorter than the select box so that the select box may still be used at its end.

将输入框放置在选择框上方并移除输入框的边框。使输入框的长度小于选择框的长度,以便选择框在其末尾仍可使用。

Use the oninput event to detect input being entered in the input box. On each keystroke check for a continuing match in the select box. When a match no longer exists there is no further need for the select box.

使用 oninput 事件检测在输入框中输入的输入。在每次击键时,在选择框中检查是否继续匹配。当匹配不再存在时,不再需要选择框。

The server will expect to receive both the text box input, if any, and the select box input, if any, and should use the select value if provided otherwise the input value if provided.

服务器将期望接收文本框输入(如果有)和选择框输入(如果有),并且应该使用选择值(如果提供)否则使用输入值(如果提供)。