使用javascript添加和删除表单行

时间:2017-07-07 06:17:01

标签: jquery html

我创建了一个表单,其中添加按钮添加表单中包含姓名,电子邮件和年龄的另一行,删除将其删除。但是,jquery代码不能按预期工作。我是jquery的初学者,弄清楚我犯了什么错误。我在Stackoverflow中查看了类似的问题,但无法弄明白。

$(document).ready(function(){
    	var max_fields= 10;
    	var wrapper  = $("#commentForm");
    	var add_button = $("#addButton");
    	var delete_button = $('#deleteButton')
    	
    	
    	var x=1;
    	add_button.click(function(e){
    		e.preventDefault();
    		
    		if (x < max_fields){
    			x++;
    			$(wrapper).append('<input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/', '<input id="bage" name="age" type="number" required/>' )
    		}
    	
    	});
    		$(wrapper).on("click","#deleteButton", function(e){
    		
    			e.preventDefault();$(this).parent('p').remove();
    			x--;
    		
    		})
    	
    	
    	});
    		
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<body>
    <section class="container">
    	<form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    	<fieldset>
    		<input type="checkbox"/>
    		
    		<p>
    			<span> Name </span> <br>
    			<label for="aname" ></label>
    			<input id="bname" name="name" minlength="2" type="text" required/>
    		</p>
    		<p>
    			<span> Email </span> <br>
    			<label for="aemail" ></label>
    			<input id="bemail" name="email" type="email" required/>
    		</p>
    		<p>
    			<span> Age </span> <br>
    			<label for="aage" ></label>
    			<input id="bage" name="age" type="number" required/>
    		</p>
    		
    			
    		<div class="input_fields_wrap">
    		
    			<div class="addButton">
    				<button  type="button" value="add">Add</button>
    			</div>
    		
    			<div class="deleteButton">
    				<button type="button" value="delete">Delete</button>
    			</div>
    		</div>
    		
    		
    	
    	</fieldset>
    	</form>
    	
    	</section>   	
    	
    		
    			
    
    </body>

谢谢。

3 个答案:

答案 0 :(得分:0)

你可以这样做

<body>
<section class="container">
    <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
    <fieldset>
        <input type="checkbox"/>
          <div id="rows">
        <P>
            <span> Name </span> </br>
            <label for="aname" ></label>
            <input id="bname" name="name" minlength="2" type="text" required/>
        </p>
        <P>
            <span> Email </span> </br>
            <label for="aemail" ></label>
            <input id="bemail" name="email" type="email" required/>
        </p>
        <p>
            <span> Age </span> </br>
            <label for="aage" ></label>
            <input id="bage" name="age" type="number" required/>
        </p>
        </div>

        <div class="input_fields_wrap">

            <div>
                <button id="addButton"  type="button" value="add">Add</button>
            </div>

            <div>
                <button  id="deleteButton" type="button" value="delete">Delete</button>
            </div>
        </div>



    </fieldset>
    </form>

    </section>

    <script>
    $(document).ready(function(){
    var max_fields= 10;
    var wrapper  = $("#commentForm");
    var add_button = $("#addButton");
    var delete_button = $('#deleteButton');
    var rows  = $("#rows");


    var x=1;
    add_button.click(function(e){
        e.preventDefault();

        if (x < max_fields){
            x++;
            rows.append('<p><input id="bname" name="name" minlength="2" type="text" required/>', '<input id="bemail" name="email" type="email" required/>', '<input id="bage" name="age" type="number" required/></p>' )
        }

    });
        delete_button.click(function(e){

            e.preventDefault();
            $( "#rows p" ).last().remove();
            x--;

        })


    });


    </script>



</body>

答案 1 :(得分:0)

所以,有些事情并不好,因为你拥有它们。

  1. ID 应该是唯一的
  2. 如果您有<span>
  3. ,为什么要使用<label>
  4. 您可以使用name="value[]"将注意力放在[]上,因此如果您提交表单,您将在服务器上获得一系列值非常棒的
  5. 你需要干净的HTML!原因是大/小写很重要
  6. 如果你有一个ID,jQuery选择器是#那么$('#my-id')如果你有一个类.所以$('.my-class')
  7. 现在我已经改变它并试图保持简单,所以应该很容易看到发生了什么。

    1. 围绕要复制/复制的字段包装。如果他们是相同的,他们几乎只是复制<div>并插入
    2. 删除了所有ID(希望您不需要它们),否则无论如何都需要清理它们。
    3. 使用小CSS隐藏第一个字段的删除按钮
    4. 为每个字段插入删除按钮,导致大多数用户将多次单击添加,然后插入数据,然后看到他们不需要所有字段,因此他们想要删除空字段。如果他们可以删除单个
    5. ,那就更简单了

      使用此代码:

      $(document).ready(function(){
        var max_fields= 10;
        var counter = 0;
        
        $('.addButton').on('click', function(){
            counter++;
            if(counter >= max_fields) {
                return;
            }
            
            var copy = $('.form-copy-wrap').first().clone();
            copy.find('.delete').removeAttr('disabled');
            $("#commentForm fieldset").append(copy);
        });
        
        $(document).on('click', '.delete', function(){
            $(this).closest('.form-copy-wrap').remove();
        });
      });
      .delete[disabled] {
          display: none;
      }
      
      .form-copy-wrap {
          border: dashed 1px #afafaf;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <section class="container">
          <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
          <fieldset>
              <input type="checkbox"/>
      
      <div class="form-copy-wrap">
              <p>
                  <label for="aname" >Name</label>
                  <input name="name[]" minlength="2" type="text" required/>
              </p>
              <p>
                  <label for="aemail" >Email</label>
                  <input name="email[]" type="email" required/>
              </p>
              <p>
                  <label for="aage" >Age</label>
                  <input name="age[]" type="number" required/>
              </p>
              <button class="delete" type="button" value="delete" disabled="disabled">Delete</button>
      </div>
      
              <div class="input_fields_wrap">
                  <div class="addButton">
                      <button  type="button" value="add">Add</button>
                  </div>
              </div>
      
      
      
          </fieldset>
          </form>

      使用复选框删除:

      $(document).ready(function(){
        var max_fields= 10;
        var counter = 0;
        
        $('.addButton').on('click', function(){
            counter++;
            if(counter >= max_fields) {
                return;
            }
            
            var copy = $('.form-copy-wrap').first().clone();
            copy.find('input[name^="delete"]').prop( "checked", false );
            $("#commentForm fieldset").append(copy);
        });
        
        $(document).on('click', '.delete', function(){
            $('input[name^="delete"]:checked').closest('.form-copy-wrap').remove();
        });
        
        $(document).on('change', 'input[name^="delete"]', function(){
            if($('input[name^="delete"]:checked').length >= 1) {
                $('.delete').removeAttr('disabled');
            } else {
                $('.delete').attr('disabled', 'disabled');
            }
        });
      });
      .delete[disabled] {
          opacity: 0.5;
      }
      
      .form-copy-wrap {
          border: dashed 1px #afafaf;
      }
      
      #commentForm .form-copy-wrap:first-child p:first-child {
          display: none;
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <section class="container">
          <form class="cmxform" id="commentForm" method="get" action="form-handler.html" autocomplete="">
          <fieldset>
      
      <div class="form-copy-wrap">
              <p>
                  <label>
                    <input type="checkbox" name="delete[]" value="delete" />
                    Delete this row
                  </label>
              </p>
      
              <p>
                  <label for="aname" >Name</label>
                  <input name="name[]" minlength="2" type="text" required/>
              </p>
              <p>
                  <label for="aemail" >Email</label>
                  <input name="email[]" type="email" required/>
              </p>
              <p>
                  <label for="aage" >Age</label>
                  <input name="age[]" type="number" required/>
              </p>
              
      </div>
      
              <div class="input_fields_wrap">
                  <div class="addButton">
                      <button  type="button" value="add">Add</button>
                  </div>
                  <button class="delete" type="button" value="delete" disabled="disabled">Delete</button>
              </div>
      
      
      
          </fieldset>
          </form>

答案 2 :(得分:0)

您的代码中存在非常小的错误。

您的代码:

var wrapper  = $("#commentForm");
var add_button = $("#addButton");
var delete_button = $('#deleteButton')

应该是这样的

var wrapper  = $("#commentForm");
var add_button = $(".addButton"); 
/* '#' is used to refer ID, '.' is used for classes*/
var delete_button = $('.deleteButton')