select - 如何将输入文本字段添加到选择元素中
问题描述
我尝试使用“chosen”(https://harvesthq.github.io/chosen/)开发一个自定义选择框。
我怎样才能在打开的选择框的底部添加一个输入文本字段(“Eigene Auflage”),如果有人点击它会在顶部添加他的值。参见图片:)
我必须将选择/选项更改为 ul/li 吗?
这是我的标记:
<select class="replace-select">
<option value="select-filled-1">Select Filled 1</option>
<option value="select-filled-2">Select Filled 2</option>
<option value="select-filled-3">Select Filled 3</option>
<option value="select-filled-4">Select Filled 4</option>
<option value="select-filled-5">Select Filled 5</option>
<option value="select-filled-6">Select Filled 6</option>
<option value="select-filled-7">Select Filled 7</option>
<option value="select-filled-8">Select Filled 8</option>
</select>
解决方案
您可以通过将文本框附加到所选创建的下拉 div 中来执行此操作,并使用事件将文本框的内容添加到原始选择中。这几乎只是使用 jQuery 将框附加到正确元素的问题。
它的工作原理是当您初始化选择时,它会隐藏选择并在几个 div 中创建一组自定义的嵌套 li。下拉 div 具有 .chosen-drop 类,因此您只需要使用 jQuery 选择带有 的元素$(".chosen-drop")
,然后使用 将文本框附加到该元素$.append(...)
。然后,您的事件处理程序只需要获取该文本框的内容并将其添加到原始选择中。
$(document).ready(function() {
//initialize the chosen.
$("#chosenSelect").chosen({
width: "100px"
});
//append text box
$("#selectContainer .chosen-drop").append('<input class = "chosen-input"/>');
//click event for enter key
$('.chosen-input').bind("enterKey", function(e) {
//get value of text box, and add it to the select.
var newValue = $(".chosen-input").val();
//insert newValue into an option HTML with template literals
var optionHTML =`<option value="${newValue}">${newValue}</option>`;
$("#chosenSelect").prepend(optionHTML).trigger("chosen:updated");
//clear the textbox after adding to the select
$(".chosen-input").val("");
});
//watch for enter key
$('.chosen-input').keyup(function(e) {
if (e.keyCode == 13) {
$(this).trigger("enterKey");
}
});
});
.chosen-input {
width: 100%
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://harvesthq.github.io/chosen/chosen.jquery.js"></script>
<link href="https://harvesthq.github.io/chosen/chosen.css" rel="stylesheet" />
<div id="selectContainer">
<label>Press enter to add new item to select</label>
<br>
<select id="chosenSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
如果您需要解释我的示例中的任何元素,请告诉我。
推荐阅读
- html - 卡片容器显示:由于边距大小问题,flex 无法正常工作
- ruby-on-rails - ActionCable 消息已保存,但在 after_create_commit 中忽略了广播
- regex - 一行命令,如果在多行标准输入中设置错误代码,则为 1,如果不是,则为 0
- ios - ScrollView 无法与 GeometryReader 一起正常工作
- url - 如何从 url 下载 m3u 文件以及帐户 iptv 的所有详细信息?
- sql-server - 在 sql server 2019 中设置 cdc 并注册 debezium sql server 连接器后运行 kafka consumer 时无法生成任何日志
- java - java.lang.OutOfMemoryError: 问题
- cygwin - 如何使用 cygwin 执行 wget 脚本?
- python - 为什么 rect 参数在 pygame 填充中不起作用?
- php - 我怎么知道我的客户端何时从不同的设备登录到我的应用程序