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

标签 php jquery datepicker

我正在尝试修改我下载的代码,该代码允许添加/删除动态添加的输入文本和下拉列表,在文件index.php中我从下拉列表中选择一个帐户名称($row["name "] 并获取帐户 ID $row["account_id"]) 并在输入字段中输入金额 (name="amount[]") ,然后使用insert.php将数据插入到Mysql数据库中。

现在我想使用日期选择器动态添加/删除输入,以便从日历(日期选择器)中选择费用发生的日期,如果我添加了多个帐户费用来注册,则每个帐户输入的日期可能不同项目,请有任何想法,我不知道该怎么做。

这是 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代码中,我有日期选择器输入字段,但不是动态添加/删除代码的一部分:

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

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

提前致谢

最佳答案

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

演示代码:

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>

关于php - 在动态添加的输入中添加日期选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65904179/

相关文章:

javascript - 在单页应用程序中上传文件

PHP 文件始终存在 False

php - undefined variable : _ENV in Laravel 5. 3

javascript - 如何从我的日历中禁用过去的日期?

php - Mysql查询的问题

javascript - 当光标悬停在图像上时显示文本

c# - 如何减少页面加载时间(结合javascript)?

javascript - 如何为单个文本字段设置占位符文本颜色的样式?

c# - 从 DatePicker DatePicked 事件设置按钮内容

javascript - Eyecom 的 Bootstrap 日期选择器似乎不起作用?