How to Add Remove input fields dynamically using jquery in HTML
×


Add/Remove input fields dynamically using jquery in HTML

3251

Dynamic input field permits giving multiple values in a form. It is very helpful when you need to get multiple inputs for the same field in an HTML form. The dynamic input fields feature can be integrated using jQuery very easily.

Add/ Remove input fields dynamically using jquery in HTML

To add or remove any input fields in HTML using jquery (for Div). You need to set two buttons, one for add and the other for remove.

To add the input fields use the following code in HTML.

<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>
</div>
</div>

<!-- 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>
</div>

<!-- 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>
</div></div></div>');

};
// 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
</script>



Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments