Menu Close

How to add and remove input fields in HTML Form using jQuery

Codeamend

Let’s see how to add and remove input fields dynamically with simple jQuery in HTML form.  You can set the maximum level as you want and also set the initial field value is required. Here, the jQuery snippet helps to duplicate/clone input fields and it stops and shows an alert message when it reaches the maximum level. 

Here, we start with one initial input field with the level of maximum is 5 including the remove button. So, when you click the add field button it will duplicate the input field one by one until it reaches the maximum level.  This same process goes to the delete button here you can just remove the current input field by clicking the individual delete button.

<div class="form-group">
    <div class="input-group">
        <input type="text" class="form-control" name="mytext[]"> <a href="#" class="remove_field"><i class="fa fa-trash">Remove</i></a>
    </div>
</div>

<button class="btn btn-primary add_input">Add Input Fields</button>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function() {
        var limit = 5; //Set limit for input fields
        var group = $(".form-group"); //Input Field Group
        var add_button = $(".add_input"); //Add input field button

        var c = 1; //initlal Input Field

        //Action for add input button click
        $(add_button).click(function(e){
            e.preventDefault();
            if(c < limit){ 
                c++;
                $(group).append('<div class="input-group"><input type="text" class="form-control" name="mytext[]"> <a href="#" class="remove_field"><i class="fa fa-trash">Remove</i></a></div>'); //add input field
            } else {
                alert('Only 5 inputs allowed');
            }
        });

        //Action for remove input button click
        $(group).on("click",".remove_field", function(e){ 
            e.preventDefault(); $(this).parent('div').remove(); c--;
        })
    });
</script> 

Output

Posted in HTML, jQuery

You can also read...