Add more dynamically in PHP

This is very common feature that you have to integrate add more feature in your application.
It could be use in adding input field or adding any div or anything.

Here I am giving steps to use this feature by simple example. In this example, I an dynamically adding First Name and Last Name in PHP form.

1.Use the following code to create dynamic form in PHP and save this file with .php extension.

File Name - index.php

<?php
$count = 0;
?>
<html>
<head>
<script type = "text/javascript" src = "jquery.js" ></script>
<script type = "text/javascript" src = "add_more.js" ></script>
</head>
<form method = "POST" action = "insert.php"> 
<div id = "count_<?php echo $count; ?>">
    FirstName<input type = "textfield" name = "firstname_<?php echo $count; ?>" value = ""><br><br>
    LastName<input type = "textfield" name = "lastname_<?php echo $count; ?>" value = ""><br><br>
</div>
<input type = "hidden" value ="<?php echo $count; ?>" name = "hidden_val" id = "hidden_val">
<input type = "button" id = "add_more" value = "Add More"><br><br>
<input type = "submit" name = "Submit" Value = "Submit">
</form>
</html>

2. Add JQuery library in your working directory. And create one java-script file in same working directory.
   In above example, I have included both JS files. Paste the following code in your java-script file.

File Name - add_more.js

 $(document).ready(function() {
 
  $("#remove").hide();
  $('#add_more').click(function() {
        return addMore();
    });
});

function addMore(){
  var hidden = parseInt($("#hidden_val").val());
  var countNewVal = hidden+1;

$('#count_'+hidden).append('<div id="count_'+countNewVal+'">FirstName<input type="textfield" value="" name="firstname_'+countNewVal+'"><br><br>LastName<input type = "textfield" name = "lastname_'+countNewVal+'" value = ""><br><br></div>');
$("#hidden_val").val(hidden+1);
}
In java-script file, I am increasing count value by 1 after every click on Add More button, And assigning that value to the hidden_val id. 

Note:- Please do not forget to add the jquery library in your working directory.  



No comments:

Post a Comment