Add or Remove Input Fields Dynamically using jQuery

Last modified on August 8, 2020 2 min read

Today I’m going to share how to make dynamic input fields using jQuery with add, remove option. Let’s start:

Table of Contents

  1. Include jQuery & Bootstrap
  2. Create a Simple Form
  3. Make Field Dynamic
  4. The Full Code
  5. Run and See the Output

Step 1 : Include jQuery & Bootstrap

It is not necessary to include Bootstrap. I’m going to include Bootstrap to make a simple design. We will include jQuery & Bootstrap’s CDNs. Here are the CDN links:

<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Step 2 : Create a Simple Form

Let’s create a simple form including one text field. We will make the text field dynamic:

<form method="post" action="">
    <div class="row">
        <div class="col-lg-12">
            <div id="inputFormRow">
                <div class="input-group mb-3">
                    <input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">
                    <div class="input-group-append">                
                        <button id="removeRow" type="button" class="btn btn-danger">Remove</button>
                    </div>
                </div>
            </div>

            <div id="newRow"></div>
            <button id="addRow" type="button" class="btn btn-info">Add Row</button>
        </div>
    </div>
</form>

Step 3 : Make Field Dynamic

We have created a simple form with one text field. We are going to make the text field dynamic using jQuery. Here’s the jQuery code:

<script type="text/javascript">
    // add row
    $("#addRow").click(function () {
        var html = '';
        html += '<div id="inputFormRow">';
        html += '<div class="input-group mb-3">';
        html += '<input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">';
        html += '<div class="input-group-append">';
        html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
        html += '</div>';
        html += '</div>';

        $('#newRow').append(html);
    });

    // remove row
    $(document).on('click', '#removeRow', function () {
        $(this).closest('#inputFormRow').remove();
    });
</script>

Step 4 : The Full Code

We have finished all the tasks. Here’s the full code:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <title>Add or Remove Input Fields Dynamically using jQuery - MyNotePaper</title>

    <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
    <div class="container"style="max-width: 700px;">

        <div class="text-center" style="margin: 20px 0px 20px 0px;">
            <a href="https://shouts.dev/" target="_blank"><img src="https://i.imgur.com/hHZjfUq.png"></a><br>
            <span class="text-secondary">Add or Remove Input Fields Dynamically using jQuery</span>
        </div>

        <form method="post" action="">
            <div class="row">
                <div class="col-lg-12">
                    <div id="inputFormRow">
                        <div class="input-group mb-3">
                            <input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">
                            <div class="input-group-append">                
                                <button id="removeRow" type="button" class="btn btn-danger">Remove</button>
                            </div>
                        </div>
                    </div>

                    <div id="newRow"></div>
                    <button id="addRow" type="button" class="btn btn-info">Add Row</button>
                </div>
            </div>
        </form>
    </div>

    <script type="text/javascript">
        // add row
        $("#addRow").click(function () {
            var html = '';
            html += '<div id="inputFormRow">';
            html += '<div class="input-group mb-3">';
            html += '<input type="text" name="title[]" class="form-control m-input" placeholder="Enter title" autocomplete="off">';
            html += '<div class="input-group-append">';
            html += '<button id="removeRow" type="button" class="btn btn-danger">Remove</button>';
            html += '</div>';
            html += '</div>';

            $('#newRow').append(html);
        });

        // remove row
        $(document).on('click', '#removeRow', function () {
            $(this).closest('#inputFormRow').remove();
        });
    </script>
</body>
</html>

Step 5 : Run and See the Output

Now let’s run this file and see the output. I’ve run and here’s the output:

The topic is over. Thanks for reading. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.
Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

30 Replies to “Add or Remove Input Fields Dynamically using jQuery”

    1. Hi اكسل ايتا,

      You can save the data to database after submitting the form. According to this tutorial, you’ll get all titles in PHP after submitting form like:

      $titles = $_POST['title'];
      $titlesJSON = json_encode($titles );

      Now you can store $titlesJSON to database. You’ll able to retrieve the data easily too.

      Thank you.

          1. Can you share the sample code to me too? I have troubled to insert the data into the database too.

  1. Thank You My code is working. Can u help me, i want to make add button that dynamically creates a field in this field user can enter their own question and can put radio buttons , checkboxes, paragraph etc..

    1. Hi Jainish, You’re welcome. Yeah, it’s possible to make dynamic radio buttons, checkboxes, paragraph etc. You can use this article’s logic. If I get free time, I’ll create and inform you. 🙂

  2. Hi Md,

    Love the script and have implemented it into a Bootstrap modal form. I was wondering if there’s a way to have the next input field added by hitting the return key as well as a plus button?

    Thank!

    1. Hello David,

      I’m sorry for late reply. I hope this code would help:

      $('#buttonID').keypress(function(event){
      var keycode = (event.keyCode ? event.keyCode : event.which);
      if(keycode == '13'){
      alert('You pressed the "enter" key');
      }
      });

      Thanks.

  3. This code is Cool! I need small help actually I dont want button to increase the input. I want the input to be increased by the number given in above input. And i want to generate different name for the generated input box with the reference to above input.

  4. Hi Md,

    Where would this code go? In controller or in the create form? How would it look , im just not sure, thanks so much great piece!

    $titles = $_POST[‘title’];
    $titlesJSON = json_encode($titles );

  5. Thanks for this. Quick question since I haven’t tested it myself.

    What if there are other form fields below the add/remove fields. If I add a field, will the fields that are not part of the add/remove inputFormRow div move down? If it doesn’t move down on add and move up on remove, how do you code that?

      1. Md, I guess my last message didn’t get saved.

        How would I create the first row to be permanent, i.e. without the option to have it removed but any additional row added has the option to be removed.

Leave a Reply