在动态添加的输入中添加日期选择器

Adding datepicker in dynamically added inputs

我正在尝试修改我下载的代码,该代码允许 add/remove 在文件 index.php 中动态添加输入文本和下拉列表,我 select 来自下拉列表($row["name"] 并获取帐户 ID $row["account_id"])并在输入字段中输入金额(name="amount[]"),然后使用 insert.php 在 [=40= 中插入数据] 数据库。

现在我想 add/remove 使用日期选择器动态输入 select 从日历(日期选择器)中获取费用发生的日期,如果我已经添加了多个帐户费用注册每个项目输入的日期可以不同,请任何想法,我不知道该怎么做。

这是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>

我的 insert.php 插入数据输入代码:

<?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';
 }
}
?>

在 index.php 代码中,我有日期选择器输入字段,但不是动态 add/remove 代码的一部分:

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

另一个问题如果我将日期选择器输入字段留在动态 add/remove 代码之外,但我只想 select 日历中的一个日期,我如何将输入日期变量传递给insert.php?

提前致谢

您只需要附加 datepicker 输入,就像您已经对其他输入所做的那样,然后在 table 中添加相同的输入后,您需要对其进行初始化。所以,你可以简单地使用 $('#item_table tr:last .datepicker').datepicker(options) 这将找到最后一个 tr 添加到你的 table 和那个 tr 中 get .datepicker 并初始化 same

演示代码 :

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>

谢谢 Swati 它有效,这是我 index.php:

的全部代码
  <?php
        //index.php
        
        //Fetch account_id from select account name from dropdownlist 
        $connect = new PDO("mysql:host=localhost;dbname=condominium", "root", "password");
        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> 
                <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>Date</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>
             <div align="center">
              <input type="submit" name="submit" class="btn btn-info" value="Insert" />
             </div>
            </div>
           </form>
          </div>
         </body>
        </html>
        
        <script>
        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>';
          html += '<td><input type="text" name="selDate[]" class="datepicker selDate" /></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();
        });
        
        //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;
          });
          
           $('.selDate').each(function(){
           var count = 1;
           if($(this).val() == '')
           {
            error += "<p>Enter Date "+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>');
          }
         });
        
        </script>

以及 insert.php 的代码:

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

拜托,我还有一个问题,下面是你帮助我之前的旧代码(我的初始代码):

 <?php
    //index.php
    
    //Fetch account_id from select account name from dropdownlist 
    $connect = new PDO("mysql:host=localhost;dbname=condominium", "root", "password");
    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

我从 table 中得到了一个日期选择器,它不是动态添加的(见附图)。

我想 select 使用动态 add/remove table 但属于表单一部分的日期选择器 (id="insert_form") 和然后将 selected 日期传递到我的 insert.php 文件,我希望使用 insert.php 插入的所有寄存器都具有与我唯一的日期选择器相同的 selected 日期。 我不知道如何在日期选择器中包含日期 selected 以及动态添加的其他输入 table 并将其传递给 insert.php?