在我的php文件中,我有:
$startDate = new DateTime('2013-08-15');
$endDate = new DateTime('2013-10-15');
echo '<div id="filterStartDate">Start Date:</div>';
echo '<div id="filterEndDate">End Date:</div>';
然后在我的javascript中:
$('#filterStartDate').datepicker({
changeMonth:true,
changeYear:true,
dateFormat:'yy-mm-dd',
onSelect: function( selectedDate ) {
$( "#filterEndDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$('#filterEndDate').datepicker({
changeMonth: true,
changeYear: true,
dateFormat:'yy-mm-dd',
onSelect: function( selectedDate ) {
$( "#filterStartDate" ).datepicker( "option", "maxDate", selectedDate );
alert($("#filterEndDate").val());
}
});
我想知道是否有办法从PHP设置datePicker的初始日期。我知道我可以从php中生成javascript,但我认为这很混乱,并希望保持分离。如果有类似的话会很棒:
echo '<div id="filterStartDate" value="'.$startDate->format('Y-m-d').'">Start Date:</div>';
答案 0 :(得分:2)
您可以使用数据属性:
$startDate = '2013-08-15'; // new dateTime() returns an object, you need a string
$endDate = '2013-10-15';
echo '<div id="filterStartDate" data-date="'.$startDate.'">Start Date:</div>';
echo '<div id="filterEndDate" data-date="'.$endDate.'">End Date:</div>';
然后让他们进入JS:
$('#filterStartDate').datepicker({
changeMonth:true,
changeYear:true,
dateFormat:'yy-mm-dd',
defaultDate: $('#filterStartDate').data('date'), // get data attribute
onSelect: function( selectedDate ) {
$( "#filterEndDate" ).datepicker( "option", "minDate", selectedDate );
}
});
$('#filterEndDate').datepicker({
changeMonth: true,
changeYear: true,
dateFormat:'yy-mm-dd',
defaultDate: $('#filterEndDate').data('date'),
onSelect: function( selectedDate ) {
$( "#filterStartDate" ).datepicker( "option", "maxDate", selectedDate );
alert($("#filterEndDate").val());
}
});
答案 1 :(得分:1)
您可以使用以下数据属性:
?>
<div id="filterStartDate" data-initial="<?= $startDate->format('Y-m-d') ?>">
Start Date:
</div>
<?php // here goes the rest of the code
...然后通过JS收集它,通过......
var initialStartDate = $('#filterStartDate').data('initial');
...然后将其发送到datepicker(作为defaultDate
选项)。
答案 2 :(得分:0)
我认为一种解决方案是不使用日历的内联选项而是使用输入。这样我就可以使用:
echo '<input type="text" id="filterStartDate" value="'.$startDate->format('Y-m-d').'" />';
如果还有其他办法,我仍然感兴趣。