Dynamically Generate Form-Fields using Jquery | Sanwebcorner

Dynamically Generate Form-Fields using Jquery

This post helps you to create and remove the form fields dynamically using jquery and Css. This is very easy to automatically generate the form fields like textbox, selectbox or any types of input fields. Now a days jquery is made all works easy

In the below example i used to add the text box, here when you click the "Add New Fields"  button it gives additional text field and also you can delete the text field using delete button in the right hand side. and also you can fix the maximum limits for your dynamically generate text boxes. Here i fixed the maximum 10 input fields, when you reached the limits you will get the alert message  like  "You Reached the limits".

This is also one of the simple method to create and remove input fields according to the user requirement, Go to the demo section you can able to view the result of this code. I hope this post is very helpful to you.



Css code for Dynamically Generate Form fields:

.container1 input[type=text] {
padding:5px 0px;
margin:5px 5px 5px 0px;
}

.add_form_field
{
    background-color: #1c97f3;
    border: none;
    color: white;
    padding: 8px 32px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 16px;
    margin: 4px 2px;
    cursor: pointer;
border:1px solid #186dad;
}

input{
    border: 1px solid #1c97f3;
    width: 260px;
    height: 40px;
margin-bottom:14px;
}

.delete{
    background-color: #fd1200;
    border: none;
    color: white;
    padding: 5px 15px;
    text-align: center;
    text-decoration: none;
    display: inline-block;
    font-size: 14px;
    margin: 4px 2px;
    cursor: pointer;
}


Javascript for Dynamically Generate Form-Fields:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
    var max_fields      = 10;
    var wrapper         = $(".container1");
    var add_button      = $(".add_form_field");
 
    var x = 1;
    $(add_button).click(function(e){
        e.preventDefault();
        if(x < max_fields){
            x++;
            $(wrapper).append('<div><input type="text" name="mytext[]"/><a href="#" class="delete">Delete</a></div>'); //add input box
        }
else
{
alert('You Reached the limits')
}
    });
 
    $(wrapper).on("click",".delete", function(e){
        e.preventDefault(); $(this).parent('div').remove(); x--;
    })
});
</script>


Html for Dynamically Generate Form-Fields:

<div class="container1">
<button class="add_form_field">Add New Field &nbsp; <span style="font-size:16px; font-weight:bold;">+ </span></button>
<div><input type="text" name="mytext[]"></div>
</div>