当用户单击添加更多时,复制选择/选项框

时间:2018-01-17 16:42:16

标签: javascript jquery html5 drop-down-menu

我想要一个简单的在线表格。表单的一个组件是显示不同员工的下拉菜单(选择/选项)。我已经在JS中填充了它:

$('#employees').append($('<option>', { value: 1, text: 'Adam' }));

但是如果用户想要添加另一个员工,我有一个他们可以点击的按钮,它应该像以前一样添加另一个下拉列表。我正在努力做到这一点。我试图将整个“代码段”附加到JS中,如下所示:

$(function() {
    $("#addMore").click(function(e) {
        e.preventDefault();
        $("#fieldList").append("<label for='employees'>Employee</label>");
        $("#fieldList").append("<div class='select-wrapper'>");
        $("#fieldList").append("<label for='employees'>Employee</label>");
        $("#fieldList").append("<select id='employees' name='employees'>");
        $("#fieldList").append("<option>- Select Employee -</option>");
        $("#fieldList").append("</select>");
        $("#fieldList").append("</div>");
        $("#fieldList").append("</div>");

    });
});

但这会导致: Duplicated the employee dropdown

显然出现了问题。部分下拉列表无法进行交互。我的问题是如何正确地做到这一点,我怎样才能做得更好?

HTML CODE

<!-- START OF EMPLOYEE -->
<div class="field third first" id="fieldList">
<label for="employees">Employee</label>
    <div class="select-wrapper">
        <select id="employees" name="employees">
            <option value="">- Select Employee -</option>
        </select>
    </div>
</div>

<div class="field third first">
    <label for="wages">Amount Paid</label>
    <input type="text" name="wages" id="wages" value=""/>
</div>

使用模板https://html5up.net/story

修改 https://jsfiddle.net/h3by56ws/(“错误”:“外壳形式无效)

1 个答案:

答案 0 :(得分:2)

Take a look at this fiddle. You only need a few lines of jQuery to do this.

请注意,您不应该拥有多个具有相同ID的DOM元素,因此您需要修改此内容。

如果你的HTML如下所示,那么你只需要这个Javascript:

&#13;
&#13;
$(function() {
    $("#addMore").click(function(e) {
        var newSelect = $("#employees").clone();
        newSelect.val("");
        $("#select-wrapper").append(newSelect);
    });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>

<div class="field third first" id="fieldList">
  <label for="employees">Employee</label>
  <div id="select-wrapper" class="select-wrapper">
    <select id="employees" name="employees">
            <option value="">- Select Employee -</option>
            <option value="1"> Bob </option>
            <option value="1"> Mark </option>
            <option value="1"> Alice </option>
            <option value="1"> Jamie </option>
            <option value="1"> Kris </option>
        </select>
  </div>
</div>
<div>
  <button id="addMore">
 Add Employee
 </button>
</div>
<div class="field third first">
  <label for="wages">Amount Paid</label>
  <input type="text" name="wages" id="wages" value="" />
</div>
&#13;
&#13;
&#13;