jQuery .remove()不适用于动态表单 [英] jQuery .remove() not working for dynamic form

查看:117
本文介绍了jQuery .remove()不适用于动态表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个动态表单,允许用户添加/删除文本字段.虽然我可以毫无问题地添加文本字段,但是在删除特定文本字段时遇到了困难.

I am creating a dynamic form that allows a user to add/remove text fields. While I can add text fields with no problem, I'm having difficulty removing specific text fields.

每当我添加其他文本字段(例如总共5个),并尝试删除除第一个文本字段之外的任何其他文本字段(例如删除字段3).它们全部消失,就像重新加载页面一样.好像当按下删除字段"时我的jQuery代码没有运行.

Whenever I add additional text fields (say a total of 5), and try to remove any of them except for the first one (say removing field 3). All of them disappear as if the page reloaded. It's as if my jQuery code doesn't run when "Remove Field" is pressed.

<form>
...
  <div id="answers">
    <div class="form-group" id="option1">
      <div class="col-xs-11 col-sm-9 col-md-6"> 
        <input class="form-control" id="answer" placeholder="Answer option">
      </div>
      <div class="col-xs-1 col-sm-1 col-md-1" style="line-height:36px;">
        <a href="" class="remove">Remove Field</span></a>
      </div>
    </div>
  </div>
...
</form>

 <div>
   <a href="" id="add">Add another field</a>
 </div>

jQuery

    <script>
        $(document).ready(function() {

            $( "#add" ).on( "click", function(event) {
                event.preventDefault();                 
                var options = $('#answers .form-group').length + 1;
                $( "#answers div:first" ).clone()
                    .attr('id', 'option' + options)
                .appendTo( "#answers" );

            });

            $( ".remove" ).on( "click", function(event) {
                event.preventDefault();                 
                $(this).closest(".form-group").remove();
            });


        });
    </script>

推荐答案

代替此:

$( ".remove" ).on( "click", function(event) {

尝试一下:

$(document).on("click", ".remove", function(event) {

这篇关于jQuery .remove()不适用于动态表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆