【问题标题】:How to add an input text field into a select element如何将输入文本字段添加到选择元素中
【发布时间】:2025-11-23 17:15:01
【问题描述】:

我尝试使用“选择”(https://harvesthq.github.io/chosen/) 开发一个自定义选择框。

如何在打开的选择框底部添加一个输入文本字段(“Eigene Auflage”),如果有人点击它会在顶部添加他的值,请参见图片:@987654322 @)

我必须将选择/选项更改为 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>

【问题讨论】:

    标签: select jquery-chosen


    【解决方案1】:

    您只需将文本框附加到所选创建的下拉 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>

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

    【讨论】: