添加数字增加的输入字段&删除字段后返回2

时间:2016-03-01 10:29:03

标签: jquery html

以下是添加名为“add”的输入字段if button的代码,点击后数值会增加(EX:数字1,数字2和等等)

当我删除添加的输入字段时,数字将继续为数字4,5。如果我再次单击“添加”按钮,它应该返回1,2,3 ......

$(function() {
  var ijk = 2;
  $("#btnAdd").bind("click", function() {
    var add = '<div class="row"><div class="col-sm-1"><strong>Domain ' + ijk + ' </strong></div>' + '<div class="col-sm-4"><input name = "DynamicTextBox"  class="form-control" type="text" value = "" /></div>' + '<div class="col-sm-1"><button class="remove btn btn-danger">cancel</button></div></div> <br />';
    $("#TextBoxContainer").append(add);
    ijk++;
  });

  $("body").on("click", ".remove", function() {
    $(this).closest(".row").remove();
  });

});
.col-sm-1 {
  float: left;
  width: 100px
}

.col-sm-4 {
  float: left;
  width: 170px
}

.row {
  clear: both
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="row">
  <div class="col-sm-1"><strong>Domain 1</strong></div>
  <div class="col-sm-4"><input type="text" 2 id="">
  </div>
  <div class="col-sm-1">
    <button id="btnAdd" type="button" class="btn btn-secondary">Add</button>
  </div>

</div>
<br>

<div id="TextBoxContainer">
  <!--Textboxes will be added here -->
</div>

1 个答案:

答案 0 :(得分:1)

检查以下代码段。

&#13;
&#13;
$(function () {
		 
      $("#btnAdd").bind("click", function (){
      var domainNumber = $('.row').length + 1; 
			var add = '<div class="row"><div class="col-sm-1"><strong>Domain '+ domainNumber +' </strong></div>' + '<div class="col-sm-4"><input name = "DynamicTextBox"  class="form-control" type="text" value = "" /></div>' + '<div class="col-sm-1"><button class="remove btn btn-danger">cancel</button></div></div> <br />';
        $("#TextBoxContainer").append(add);
				
  });
                                
       $("body").on("click", ".remove", function () {
           $(this).closest(".row").remove();
       });
								
 });
&#13;
.col-sm-1{float:left; width:100px}
.col-sm-4{float:left;width:170px}
.row{clear:both}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
			<div class="col-sm-1"><strong>Domain 1</strong></div>
			<div class="col-sm-4"><input type="text" 2 id="">
</div>
			 <div class="col-sm-1">
			<button id="btnAdd"  type="button" class="btn btn-secondary">Add</button>
       </div>
							  
</div>
		<br>
					     
   <div id="TextBoxContainer">
        <!--Textboxes will be added here -->
   </div>
&#13;
&#13;
&#13;