我试图将jQuery datepicker值存储到php日期格式的变量中。
期望的结果:示例
输入字段名称“reviewdate”=03/02/2015
输入字段名“reviewmonth”=3
这两个值都将提交到mysql数据库。我可以存储“reviewdate”,但在信息提交到数据库后,“reviewmonth”仍为“空”。
<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!
最佳答案
要使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