在选择框中显示文本框的值

时间:2018-07-13 13:32:03

标签: jquery

我试图在选择中显示文本框的值。例如,如果您在ChairpersonPresidentVicePresident文本字段中键入任何内容,则这些文本框的值应在select中作为选项单独显示。

我尝试了以下操作,但不起作用。

$(document).ready(function() {
  $("#Chairperson_change").change(function() {
    document.getElementById("dropdown_change").value = document.getElementById("Signatories").value;
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Chairperson: <input name="Chairperson" type="text" maxlength="50" id="Chairperson_change" style="width: 665px; padding:0px; z-index: 2; position: absolute;" /><br> 
President: <input name="President" type="text" maxlength="50" style="width: 665px; padding:0px; z-index: 2; position: absolute;"
/><br> 
VicePresident: <input name="VicePresident" type="text" maxlength="50" style="width: 665px; padding:0px; z-index: 2; position: absolute;" /><br>

<select id="dropdown_change"><br>
  <option value="">Options here</option>
</select>

1 个答案:

答案 0 :(得分:3)

要实现此目的,您可以挂钩到文本框的input事件。然后,您可以为每个文本框(基于其option)创建新的id元素,或者如果已经存在,则对其进行更新。试试这个:

$(function() {
  $(".position").on('input', function() {
    var $option = $(`#dropdown_change option[data-pos="${this.id}"]`);
    if (!$option.length)
      $option = $(`<option data-pos="${this.id}" />`);

    $option.text(this.value).val(this.value).appendTo('#dropdown_change');
  });
});
.position {
  width: 665px;
  padding: 0px;
  z-index: 2;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Chairperson: <input name="Chairperson" id="chair" type="text" maxlength="50" class="position" /><br /> 
President: <input name="President" id="pres" type="text" maxlength="50" class="position" /><br /> 
VicePresident: <input name="VicePresident" id="vice" type="text" maxlength="50" class="position" /><br />

<select id="dropdown_change">
  <option value="">Options here</option>
</select>