Skip to content
Advertisement

Adding datepicker in dynamically added inputs

I’m trying to modify a code I downloaded, the code permits to add/remove dynamically added inputs text and a dropdownlist, in file index.php I select an account name from dropdownlist ($row["name"] and fetch the account Id $row["account_id"]) and enter an amount in a input field (name="amount[]"), then an insert the data using insert.php in Mysql database.

Now I want to add/remove a input dynamically with a datepicker for selecting from the calendar (datepicker) the date in which the expense was made and if I have add several account expense to register the dates entered can be different for each item, Please Any ideas, I don’t know how to do it.

This is Index.php:

<?php
//index.php

//Fetch account_id from select account name from dropdownlist 
$connect = new PDO("mysql:host=localhost;dbname=condominium", "root", "mysq1passw0rd");
function fill_unit_select_box($connect)
{ 
 $output = '';
 $query = "SELECT * FROM accounts ORDER BY name ASC";
 $statement = $connect->prepare($query);
 $statement->execute();
 $result = $statement->fetchAll();
 foreach($result as $row)
 {
  $output .= '<option value="'.$row["account_id"].'">'.$row["name"].'</option>';
 }
 return $output;
}
?>
<!DOCTYPE html>
<html>
 <head>
  <title>Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
 </head>
 <body>
 

  <br />
  <div class="container">
   <h3 align="center">Add Remove Select Box Fields Dynamically using jQuery Ajax in PHP</h3>
   <form method="post" id="insert_form">
    <div align="left">
       <h4 align="center">Enter Expense Details</h4> 
                <!-- Asi abre directamentete Modal usando  data-target="#userModal -->  
                <!-- <button type="button" class="btn btn-success" data-toggle="modal" data-target="#AddModal">Agregar Emp.</button>--> 
                <!-- Con Input hay que enviarlo primero a ajax y ajax abre modal -->                
                <label style="color: blue" >Select Date</label> 
                <div><input type="text" name="selDate" id="datepicker"class="tcalx" value="" /></div>
                <!-- <input type="text" class="form-control" placeholder="1000" name="preciobsmayor" id="preciobsmayor" readonly="readonly"><br>-->
                <br /> 
                <br />
    </div>
    <div class="table-repsonsive">
     <span id="error"></span>
     <table class="table table-bordered" id="item_table">
      <tr>
       <th>Account </th>
       <th>Amount</th>
       <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus"></span></button></th>
      </tr>
     </table>
     <div align="center">
      <input type="submit" name="submit" class="btn btn-info" value="Insert" />
     </div>
    </div>
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){
 
 $(document).on('click', '.add', function(){
  var html = '';
//Add Dropdownlist and Input 
 html += '<tr>';
  html += '<td><select   name="account_id[]" class="form-control account_id"><option value="">Select Product</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><input type="text" name="amount[]" class="form-control amount" /></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';
  $('#item_table').append(html);
 });
 
 $(document).on('click', '.remove', function(){
  $(this).closest('tr').remove();
 });
 
 //Give Messages asking for entering Data
 $('#insert_form').on('submit', function(event){
  event.preventDefault();
  var error = '';
  $('.account_id').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Select Account Name at "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
  $('.amount').each(function(){
   var count = 1;
   if($(this).val() == '')
   {
    error += "<p>Enter Amount "+count+" Row</p>";
    return false;
   }
   count = count + 1;
  });
  
 //Send Data To Insert in Mysql
  var form_data = $(this).serialize();
  if(error == '')
  {
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     if(data == 'ok')
     {
      $('#item_table').find("tr:gt(0)").remove();
      $('#error').html('<div class="alert alert-success">Expense Saved</div>');
     }
    }
   });
  }
  else
  {
   $('#error').html('<div class="alert alert-danger">'+error+'</div>');
  }
 });
 
});


//Dateicker Function not insert en rows
$(function() {
    $("#datepicker").datepicker({
       //showOn: both - datepicker will appear clicking the input box as well as the calendar icon
       //showOn: button - datepicker will appear only on clicking the calendar icon
       showOn: 'button',
       //you can use your local path also eg. buttonImage: 'images/x_office_calendar.png'
       buttonImage: 'https://theonlytutorials.com/demo/x_office_calendar.png',
       buttonImageOnly: true,
       changeMonth: true,
       changeYear: true,
       showAnim: 'slideDown',
       duration: 'fast',
       dateFormat: 'dd-mm-yy'
    });
});

</script>

This My insert.php code for insert data entered:

<?php
//Insert Data

if(isset($_POST["account_id"]))
{
 $connect = new PDO("mysql:host=localhost;dbname=condominium", "root", "mysq1passw0rd");
 $order_id = uniqid();
 for($count = 0; $count < count($_POST["account_id"]); $count++)
 {  
  $query = "INSERT INTO expense 
  (account_id, amount) 
  VALUES (:account_id, :amount)
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':account_id'  => $_POST["account_id"][$count], 
    ':amount' => $_POST["amount"][$count], 
   )
  );
 }
 $result = $statement->fetchAll();
 if(isset($result))
 {
  echo 'ok';
 }
}
?>

In the index.php code I have the datepicker input field but isn’t part of the dynamically add/remove code:

<label style="color: blue" >Select Date</label> 
                <div><input type="text" name="selDate" id="datepicker"class="tcalx" value="" /></div>

Another question If I leave the datepicker input field out the of the dynamically add/remove code, but I want to select just one date in calendar, How can I pass the input date variable to insert.php?

Thanks in advance

Advertisement

Answer

You just need to append datepicker inputs like you are already doing for other inputs then after adding same inside your table you need to initialize it . So , you can simply use $('#item_table tr:last .datepicker').datepicker(options) this will find last tr added inside your table and inside that tr get .datepicker and initialize same

Demo Code :

var options = {
  showOn: 'button',
  buttonImage: 'https://theonlytutorials.com/demo/x_office_calendar.png',
  buttonImageOnly: true,
  changeMonth: true,
  changeYear: true,
  showAnim: 'slideDown',
  duration: 'fast',
  dateFormat: 'dd-mm-yy'
}
$(document).on('click', '.add', function() {
  var html = '';
  //Add date input use `class` adjust it accroding to your need
  html += '<tr>';
  html += '<td><select   name="account_id[]" class="form-control account_id"><option value="">Select Product</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><input type="text" name="amount[]" class="form-control amount" /></td><td><input type="text" name="selDate" class="datepicker tcalx" value="" /></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus">-</span></button></td></tr>';
  $('#item_table').append(html);
  //get tr last added and inside that datpicker initialize it..
  $('#item_table tr:last .datepicker').datepicker(options);
});

$(document).on('click', '.remove', function() {
  $(this).closest('tr').remove();
});
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css">
<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>

<table class="table table-bordered" id="item_table">
  <tr>
    <th>Account </th>
    <th>Amount</th>
    <th><button type="button" name="add" class="btn btn-success btn-sm add"><span class="glyphicon glyphicon-plus">Add</span></button></th>
  </tr>
</table>
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement