PHP jQuery Dynamic Textbox

This tutorial helps to add or remove textbox dynamically using jQuery and PHP. It also describes how to read the values of dynamically created textboxes and save them to the database.

  1. Save textbox HTML in separate file.
  2. Load and append dynamic textbox.
  3. Remove textbox item on delete event.
  4. Read and insert data to database on submit.


Download PHP jQuery Dynamic Textbox Source CodeLive Demo

Textbox HTML

Save this code as input.php. This file will be loaded later using jQuery to append textbox HTML code to the target location.

<DIV class="product-item float-clear" style="clear:both;">
<DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV class="float-left"><input type="text" name="item_name[]" /></DIV>
<DIV class="float-left"><input type="text" name="item_price[]" /></DIV>

Load and Append Dynamic Textbox

The textbox markup will be added dynamically by using jQuery append() and load(). The code is,

function addMore() {
   $("<DIV>").load("input.php", function() {

Remove Textbox

We have checkbox for each row dynamically added textbox for selecting rows to be removed on delete event. And script for removing checked items is,

function deleteRow() {
   $('DIV.product-item').each(function(index, item){
      jQuery(':checkbox', this).each(function () {
         if ($(this).is(':checked')) {

Read Dynamic Textbox Input

This is as usual we have seen in several MySQL crud examples. The code is,

if(!empty($_POST["save"])) {
   $conn = mysql_connect("localhost","root","");
   $itemCount = count($_POST["item_name"]);
   $query = "INSERT INTO item (item_name,item_price) VALUES ";
   $queryValue = "";
   for($i=0;$i<$itemCount;$i++) {
      if(!empty($_POST["item_name"][$i]) || !empty($_POST["item_price"][$i])) {
	 if($queryValue!="") $queryValue .= ",";
  	 $queryValue .= "('" . $_POST["item_name"][$i] . "', '" . $_POST["item_price"][$i] . "')";
   $sql = $query.$queryValue;
   if($itemValues!=0) {
      $result = mysql_query($sql);
      if(!empty($result)) $message = "Added Successfully.";

Download PHP jQuery Dynamic Textbox Source CodeLive Demo

This PHP code tutorial was published on July 21, 2014.

↑ Back to Top