Add/Remove input fields dynamically using jquery in HTML

by Lalita 07-May-19

0 241

Question: Add/ Remove input fields dynamically using jquery in HTML
Answer: To add or remove any input fields in html using jquery (for Div). You need to set two buttons, one for add and other for remove.

<div class="col-md-6">
<div class="form-group">
<label for="exampleInputName"> Topic Name </label>
<input type="text" class="form-control" name="topic_name[]"
placeholder="Topic Name" required>

<!-- Here in the div "add_topic" class is used to show the add more field -->
<!-- You have to make the particular section where you want to show the input fields,
so that when you add section it will not Effect the UI -->

<!-- Start div where it will show the added fields -->
<div class="col-md-12 add_topic"> </div>

<!-- End Div -->

<!-- Buttons to add or remove section -->
<!-- Start Div -->

<div class="form-group col-md-12">
<button type="button" id="addButton" class="btn btn-primary btn-sm" name="add"
style="font-size:11px;" onclick="addTopic(5)"> Add More </button>

<!-- Here 5 is the maximum limit to set -->

<button type="button" id="removeButton" class="btn btn-danger btn-sm" name="remove"
style="font-size:11px;" onclick="removeButton()"> Remove Field </button>

<!-- End Div -->

<!-- The below script you can call in footer or also at bottom of your page -->

<script type="text/javascript">
function addTopic(uplimit){
// If you want to set the limit for adding fields you can use the below code
// If you don't want to set limit, then use can remove or comment the below "If" condition

if( ($('.form .control-group').length+1) > uplimit-1) {
alert("You can add maximum 5 .");
return false;
// Below is the code to add the section
// starting of add fields

var id = ($('.add_topic .control-group').length + 0).toString();
$('.add_topic').append('<div class="control-group" id="control-group' + id + '">
<div class="col-md-6"><div class="form-group"><label for="exampleInputName">Topic Name</label>
<input type="text" class="form-control" name="topic_name[]" placeholder="Topic Name" required>

// ending of add fields

// starting for remove fields
$(document).ready(function () {
$("#removeButton").click(function () {
if ($('.add_topic .control-group').length == 0) {
alert("No more textbox to remove");
return false;
$(".add_topic .control-group:last").remove();

// Ending for remove fields code


Discount Coupons

SEMRush FREE Trial – PRO Account for 14 Days

FREE Pro Account worth $99.95 for 14 Days.


    No Comments Yet.

Leave a Reply