How to add / remove input fields dynamically with jQuery

In this tutorial, we will see how we can dynamically add or remove input fields using jQuery.

Useful Read: Count Characters Remaining with jQuery

Add/Remove Input Fields Dynamically using jQuery

Add/Remove Input Fields Dynamically using jQuery

Click Here to view the working demo.

HTML:

<div class="wrapper">
	<button id="addField">Add Field</button></a>
	<div id="p_scents">
    	<p>
    	    <label for="p_scnts">
    	    	<input type="text" id="p_scnt" size="20" name="p_scnt" value="" placeholder="Input Value" />
    	    </label>
    	</p>
	</div>
</div>

CSS:

<style type="text/css">
	p { 
		padding:0 0 5px 0; 
	}

	input { 
		padding:5px; 
		border:1px solid #999; 
		border-radius:4px; 
	}
	#addField {
		background-color: #55ACEE;
		padding: 5px;
		border-radius: 20px;
		font-weight: 700;
	}
	#removeField {
		background-color: #C83737;
		padding: 5px;
		border-radius: 20px;
		font-weight: 700;
	}
	.wrapper {
		margin: 0px auto;
		width: 500px;
	}
  </style>

jQuery:

<script type="text/javascript">
  $(document).ready(function(){
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;
        
        $('.wrapper').on('click','#addField' , function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label><button id="removeField">Remove</button>').appendTo(scntDiv);
                i++;
                return false;
        });
        
        $('.wrapper').on('click','#removeField', function() { 
                if( i > 2 ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
   });
  </script>

 

0 Comments

Leave a Comment.