首页 > 解决方案 > 如何将输入文本字段添加到选择元素中

问题描述

我尝试使用“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>

标签: selectjquery-chosen

解决方案


您可以通过将文本框附加到所选创建的下拉 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>

如果您需要解释我的示例中的任何元素,请告诉我。


推荐阅读