Add or Remove Input Fields Dynamically using jQuery

Last modified on August 8, 2020 2 min read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

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://www.mynotepaper.com/" 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. 🙂

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

16 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. 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.

    1. Hi,
      You can do it easily. Take input number and run jQuery loop. In the loop, append the field code.
      You won’t able to make different names. You need to use the same name as field_name[].
      Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *