How to add remove dynamic text field in jquery

dynamic text field to add and remove using jQuery, This tutorial we are going to implement this.  Idea is simple when user click on add button we append text after div after is jQuery function. When user click on remove button we use remove jQuery function. 
How to add remove dynamic text field in jquery

Create file in working directory

<!DOCTYPE html>
<html>
 
<head>
  <title>How to add remove dynamic text field in jquery</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" />
</head>
 
<body class="container">
  <div class="row mt-3">
	<div class="form-group optionBox">
		<div class="row">
			<div class="col-md-12">
				<div class="block">
					<div class="input-group" style="margin-bottom:8px;"  id="1">
						<input type="text" name="btn_label[]" class="form-control btn_label" placeholder="Add Button Label">
						<span class="input-group-btn"> 
							<button type="button"  class="btn btn-primary addButton">+</button> 
						</span>
					</div>
				</div>
			</div>
		</div>
	</div>
  </div>
</body>

<script>
	var i=1;
	$('.addButton').click(function() {
		i++;
		var html='<div class="input-group" style="margin-bottom:8px;"><input type="text" name="btn_label[]" class="form-control btn_label" placeholder="Add Button Label" value=""><span class="input-group-btn"><button type="button"  class="btn btn-primary remove">-</button> </span></div>';
		$('.block:last').after('<div class="block" id="'+i+'">'+html+'</div>');
	});
	
	$('.optionBox').on('click','.remove',function() {
		var id=$(this).parent().parent().attr("id");
		//alert(id);
		$(this).parent().parent().remove();
	});
</script>
 
</html>

Leave a Reply