jQuery动态添加和删除字段

时间:2018-08-23 12:29:36

标签: javascript jquery html bootstrap-4

我希望有一个动态表单,您不能在其中添加和删除字段。我使用bootstrap 4和jquery(最新的苗条版本)。

通过单击“添加”,通过克隆第一个元素来生成新字段。问题是我只能删除最后一个元素,但不能删除最后一个元素之前的其他元素。通过单击“删除”,没有任何反应。

我刚刚将代码添加到jsfiddle中,因此您可以实时查看它:https://jsfiddle.net/2mrpd8s4/

我的实际代码是:

index.html:

<!DOCTYPE html>
<html>
<head>
  <title>Some title</title>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
</head>
<body>
  <div class="card">
    <div class="card-body">
      <p><button type="button" class="btn btn-outline-primary btn-add">Add</button></p>
      <div class="form-row form-add">
        <div class="form-group col-sm-11">
          <input type="text" class="form-control" placeholder="Value">
        </div>
        <div class="form-group col-sm-1">
          <button type="button" class="btn btn-outline-danger btn-remove">Remove</button>
        </div>
      </div>
    </div>
  </div>
  <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
  <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"></script>
  <script src="main.js"></script>
</body>
</html>

main.js:

$(document).ready(function() {
    $(".form-add:first .btn-remove").hide();

    $(".btn-add").click(function() {
        $(".form-add:first").clone().find("input:text").val("").end().insertBefore(".form-add:first");
        $(".form-add:not(:first) .btn-remove").show();
    });

    $(".btn-remove").on("click", function() {
        $(this).parent().parent().remove();
    });
});

感谢您的帮助。

0 个答案:

没有答案