jQuery Datepicker值并存储到php变量中

时间:2015-03-03 06:05:23

标签: javascript php jquery html mysql

我正在尝试将jQuery datepicker值存储到php日期格式的变量中。

期望的结果:示例

输入字段名称" reviewdate" = 03/02/2015

输入字段名称" reviewmonth" = 3

这两个值都将提交给mysql数据库。我可以存储" reviewdate",但" reviewmonth"遗骸" null"将信息提交到数据库之后。

<body>

   <!-- Datepicker -->
   <h2 class="demoHeaders">Datepicker</h2>

   <input name="reviewdate" type="text" id="datepicker"></input>

   <input name="reviewmonth" type="hidden"  value="<?php if(isset($_GET["reviewdate"])) { echo date_format($_GET["reviewdate"], "n");} else {echo "";} ?>"></input>

   <script src="external/jquery/jquery.js"></script>
   <script src="jquery-ui.js"></script>
   <script>
      $( "#datepicker" ).datepicker({
         inline: true
      });
  </script>
</body?

Thank you so much for all your help!

2 个答案:

答案 0 :(得分:2)

要使date_format正常工作,您需要先初始化DateTime对象:

<?php 
$month = '';
if(isset($_GET["reviewdate"])) { 
    $date = new DateTime($_GET["reviewdate"]); // or $date = date_create($_GET["reviewdate"]); will work the same
    $month = date_format($date, "n");
}
?>
<input name="reviewmonth" type="hidden" value="<?php echo $month; ?>"></input>

如果你想在JS中这样做,你需要为datepicker添加一个处理程序来处理reviewmonth并将其附加到隐藏的输入中:

<?php

if(isset($_POST['submit'])) {
    echo '<pre>', print_r($_POST), '</pre>';
}

?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css" />
<form method="POST">
    <input name="reviewdate" type="text" id="datepicker" />
    <input name="reviewmonth" type="hidden" value="" />
    <input type="submit" name="submit" />
</form>

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script type="text/javascript">
$('#datepicker').datepicker({
    inline: true,
    onSelect: function(dateText, inst){
        var date = $(this).val();
        var d = new Date(date);
        var n = (d.getMonth() + 1);
        $('input[name="reviewmonth"]').attr('value', n);
    }
});
</script>

Sample Output

答案 1 :(得分:1)

你必须替换这个

 <script>
  $( "#datepicker" ).datepicker({
     inline: true
  });
  </script>

 <script>
  $( "#datepicker" ).datepicker({
     inline: true,
    dateFormat: 'Y-m-d'
  });
 </script>