Appending form inputs within a form using Jquery

Learning by examples is the way we do and as we often ask us about JQuery tutorials, today we are adding a new one which will be followed with further integration such as Ajax calls and API programming.

Example of appending form inputs inside a form

JQuery offers such a powerful tools’ set, it would be dumb not to use it for our projects. We will also use Bootstrap in our example to design our simple form.

Upon submission of the form, the data will be displayed on the page.

Check out the end result so you get a better understanding of what we do :

Append form inputs jquery

Demo page of appending form inputs in a table.

Form structure and coding

Before diving into the code for implementing the required behavior, we need to load the CSS and javascript libraries respectively from Bootstrap and JQuery.

You may use CDN servers to load the scripts but here we do it locally :

<!DOCTYPE HTML>
<html>
<head>
<title>Title of your choice</title>
<meta http-equiv="Content-type" content="text/html; charset=UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script type="text/javascript" language="javascript" src="jquery-3.2.1.min.js"></script>
<link href="bootstrap-3.3.7-dist/css/bootstrap.min.css" type="text/css" rel="stylesheet" />

With Bootstrap you can also include the revisited JQuery library, check their website for more details.

We implement HTML5 and add a meta to handle responsive design correctly (viewport).

Our form is inserted inside a container for proper rendering :


<div class="container" style="margin-bottom:50px;">
    <!-- Header of our table with default form data not to be passed on dynamic rows -->

<form method="POST" action="fill-form-rows-jquery-array.php" class="form-horizontal">
        
<div class="form-group">
         <label for="inputDay" class="col-sm-2 control-label">Day</label>
         
<div class="col-sm-10">
          <input type="number" class="form-control" id="inputDay" placeholder="" name="day" min="1" max="31"/>
         </div>

       </div>

       
       
<div class="form-group">
        <label for="inputMonth" class="col-sm-2 control-label">Month</label>
        
<div class="col-sm-10">
         <input type="number" class="form-control" id="inputMonth" placeholder="" name="month" min="1" max="12" />
        </div>

       </div>

      
    
<div class="form-group">
     <label for="inputCode" class="col-sm-2 control-label">Car</label>
     
<div class="col-sm-10">
       <select class="form-control" name="car">
<option value="0">--Please select--</option>
<option value="1">BMW</option>
<option value="2">PEUGEOT</option>
<option value="3">FORD</option>
<option value="4">NISSAN</option>
       </select>
    </div>

  </div>

      
  
<div class="form-group">
     <label for="inputMessage" class="col-sm-2 control-label">Message</label>
     
<div class="col-sm-10">
      <input type="text" class="form-control" id="inputMessage" placeholder="" name="message" />
     </div>

  </div>

 
  <a class="btn btn-default" id="add" href="#" role="button"><span class="glyphicon glyphicon-plus"></span>&nbsp;Add entry</a> 

  
<table class="table" id="mytable">
   
<tr>
   
<th>ID</th>

   
<th>Purpose</th>

   
<th>Amount</th>

   
<th>Currency</th>

   
<th>Currency ratio</th>

   </tr>

 </table>

    
 <button type="submit" class="btn btn-primary">Submit</button>
</form>


</div>

There is no difficulties here as it’s only pure HTML along with Bootstrap styling.

We see a table which will welcome additional entries for the form as rows.

Our button : Add entry

needs to be attached with an event.

Declaring the event to add new rows

Below the container of our form we will add a function to catch the click of the above button and insert the html code inside the table :

<!-- Jquery script to add one more row inside the table -->
<script>
$( "#add" ).click(function() {

var newElement = '<tr><td><input type="text" value="" name="id[]" placeholder="4.."/></td><td><input type="text" value="" name="purpose[]" placeholder="Why do you buy this car?"/></td><td><input type="number" value="" name="amount[]" placeholder="0"/></td><<td><input type="text" value="" name="currency[]" placeholder="EUR"/></td><td><input type="number" value="" name="ratio[]" placeholder="1"/></td></tr>';
$( "#mytable" ).append( $(newElement) );

});
</script>

The important thing is to attach the event to the right button identified by its ID : #add.

All the rest of the script is obvious, a new html element representing a table row is appended and you may add any number of rows you need.

Retrieving the submitted data

Using Php, we will simply receive the data from the form and display it on the page. Trimming and stripping tags for security matters is implemented on top of the printing :


<div class="container" style="margin-bottom:50px;">

<?php

// Avoid spaces and tags within script :
$_POST["day"] = trim(strip_tags($_POST["day"]));
$_POST["month"] = trim(strip_tags($_POST["month"]));
$_POST["message"] = trim(strip_tags($_POST["message"]));
$_POST["car"] = trim(strip_tags($_POST["car"]));

echo '<p>You ordered the car : '.$_POST['car'].' on '.$_POST['day'].'/'.$_POST['month'].' this year.<br/>';
echo 'Message : '.$_POST['message'].'</p>';

echo '<h2>Row elements</h2>';

// Get the size of array :
$size = sizeof($_POST['id']);

// Browse each element and display them :
for ($i = 0;$i < $size;$i++)
{

echo '<div class="row">
<div class="col-md-2">'.trim(strip_tags($_POST["id"][$i])).'</div>
<div class="col-md-4">'.trim(strip_tags($_POST["purpose"][$i])).'</div>
<div class="col-md-2">'.trim(strip_tags($_POST["amount"][$i])).'</div>
<div class="col-md-2">'.trim(strip_tags($_POST["credit"][$i])).'</div>
<div class="col-md-1">'.trim(strip_tags($_POST["currency"][$i])).'</div>
<div class="col-md-1">'.trim(strip_tags($_POST["ratio"][$i])).'</div>
</div>';
}

?>
</div>

We just keep using the Bootstrap library for this resulting page but you don’t need to load the JQuery package.

I hope you enjoyed the example, if you have any questions, do not hesitate, I will be glad to answer.

In a next example, I’ll show you how to deal with Ajax to retrieve some data from an external URL.

Leave a Reply

Want more information?

Related links will be displayed here in this section for you to pick up another good spot to get more details about Web marketing and Search Engine Optimization. There will be some sites which we selected to ease the work of any webmaster or/and web marketer on the Internet.

%d bloggers like this: