Clue Mediator

Add or remove input fields dynamically in PHP using jQuery

📅June 3, 2020
🗁PHP

Today we’ll show you how to add or remove input fields dynamically in PHP using jQuery. Previously we have implemented the same type of the functionality to add or remove input fields dynamically in React.

In this article, we will see an example to add multiple fields with the remove button and how to get field value after form submission using PHP. Also we can remove the added fields by clicking on the remove link.

Steps to add or remove input fields dynamically

  1. Create HTML form
  2. Add jQuery library
  3. Add jQuery script
  4. Get values using PHP
  5. Output

1. Create HTML form

Let’s create a HTML form with a single input field and `Add More` button.

<form method="post">
  <div class="wrapper">
    <div class="input-box">
      <input type="text" name="input_name[]">
      <button class="btn add-btn">Add More</button>
    </div>
  </div>
  <input type="submit" class="btn" value="Submit">
</form>

Also use the following style to design the page.

<style>
  body {
    font-family: arial;
    padding-left: 10px;
  }

  .input-box {
    margin: 15px 0;
  }

  .input-box input {
    padding: 5px 10px;
    border-radius: 2px;
    border: 1px solid #999;
  }

  .btn {
    cursor: pointer;
    padding: 5px 10px;
    border-radius: 2px;
    border: 1px solid #17a2b8;
    color: #fff;
    background-color: #17a2b8;
  }

  .btn:hover {
    background-color: #138496;
    border-color: #117a8b;
  }

  .btn:focus {
    outline: 0;
  }

  .input-box a {
    color: red;
    font-size: 13px;
    text-decoration: none;
  }

  .input-box a:hover {
    text-decoration: underline;
  }
</style>

2. Add jQuery library

We have to add the following jQuery library in the head section of the page.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

3. Add jQuery script

Let’s write a code to add or remove elements from the DOM using jQuery.

<script type="text/javascript">
  $(document).ready(function () {

    // allowed maximum input fields
    var max_input = 5;

    // initialize the counter for textbox
    var x = 1;

    // handle click event on Add More button
    $('.add-btn').click(function (e) {
      e.preventDefault();
      if (x < max_input) { // validate the condition
        x++; // increment the counter
        $('.wrapper').append(`
          <div class="input-box">
            <input type="text" name="input_name[]"/>
            <a href="#" class="remove-lnk">Remove</a>
          </div>
        `); // add input field
      }
    });

    // handle click event of the remove link
    $('.wrapper').on("click", ".remove-lnk", function (e) {
      e.preventDefault();
      $(this).parent('div').remove();  // remove input field
      x--; // decrement the counter
    })

  });
</script>

In the above script, we have set a maximum limit of input fields that indicates the user can add maximum `5` input fields but you can change it as per your requirements.

When the user clicks on the `Add More` button then a new input field with remove link will be added until the count reaches maximum limit. Similarly when the user clicks on the Remove link, the relevant input field will be removed.

4. Get values using PHP

After the form submission, we will get the value of input fields in the type of the array like below.

<!--?php
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){ <p-->

  echo '<pre>';
  print_r($_POST["input_name"]);
  echo '</pre>';

  $input_name = $_POST["input_name"];
  foreach($input_name as $field_value){
    // your insert query goes here...
  }
  exit;
}
?>

We have also shown you the logic to loop through each item where you can insert it into the database table.

5. Output

Combine all codes together and see how it works.

index.php

<!--?php
if (isset($_POST["input_name"]) && is_array($_POST["input_name"])){ <p-->

  echo '<pre>';
  print_r($_POST["input_name"]);
  echo '</pre>';

  $input_name = $_POST["input_name"];
  foreach($input_name as $field_value){
    // your insert query goes here...
  }
  exit;
}
?>





  <title>Dynamically add or remove input fields - Clue Mediator</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <style>
    body {
      font-family: arial;
      padding-left: 10px;
    }

    .input-box {
      margin: 15px 0;
    }

    .input-box input {
      padding: 5px 10px;
      border-radius: 2px;
      border: 1px solid #999;
    }

    .btn {
      cursor: pointer;
      padding: 5px 10px;
      border-radius: 2px;
      border: 1px solid #17a2b8;
      color: #fff;
      background-color: #17a2b8;
    }

    .btn:hover {
      background-color: #138496;
      border-color: #117a8b;
    }

    .btn:focus {
      outline: 0;
    }

    .input-box a {
      color: red;
      font-size: 13px;
      text-decoration: none;
    }

    .input-box a:hover {
      text-decoration: underline;
    }
  </style>



  <h4>Dynamically add or remove input fields - <a href="https://www.cluemediator.com" target="_blank" rel="noopener noreferrer">Clue Mediator</a></h4>

  <form method="post">
    <div class="wrapper">
      <div class="input-box">
        <input type="text" name="input_name[]">
        <button class="btn add-btn">Add More</button>
      </div>
    </div>
    <input type="submit" class="btn" value="Submit">
  </form>

  <script type="text/javascript">
    $(document).ready(function () {

      // allowed maximum input fields
      var max_input = 5;

      // initialize the counter for textbox
      var x = 1;

      // handle click event on Add More button
      $('.add-btn').click(function (e) {
        e.preventDefault();
        if (x < max_input) { // validate the condition
          x++; // increment the counter
          $('.wrapper').append(`
            <div class="input-box">
              <input type="text" name="input_name[]"/>
              <a href="#" class="remove-lnk">Remove</a>
            </div>
          `); // add input field
        }
      });

      // handle click event of the remove link
      $('.wrapper').on("click", ".remove-lnk", function (e) {
        e.preventDefault();
        $(this).parent('div').remove();  // remove input field
        x--; // decrement the counter
      })

    });
  </script>

Check out the output in the browser.

Output - Add or remove input fields dynamically in PHP using jQuery - Clue Mediator

Output - Add or remove input fields dynamically in PHP using jQuery - Clue Mediator

That’s it for today.
Thank you for reading. Happy Coding..!!