单击按钮时切换DateTimePicker视图

时间:2016-07-27 07:05:30

标签: jquery twitter-bootstrap bootstrap-datetimepicker

我在项目中使用DateTimePicker 3 Bootstrap作为我的日历。如果单击某些按钮,我需要将“datetimepicker”视图从“月到日”或“日期到月”切换。我尝试使用jQuery但它根本不工作。 请检查我是否在代码中犯了错误。

我目前的标记和脚本代码:

<script>
$(document).ready(function(){
    $("#Month").click(function () {
        $('#datetimepicker3').datetimepicker({
            format: 'M-YYYY',
            maxDate: 'now'
        });
    });
    $("#Date").click(function () {
        $('#datetimepicker3').datetimepicker({
            format: 'DD-MM-YYYY',
            maxDate: 'now'
        });
    });
});
</script>

<div class="form-group">
    <div class='input-group date' id='datetimepicker3'>
        <input type='text' class="form-control" name="date" />
        <span class="input-group-addon">
            <span class="glyphicon glyphicon-time"></span>
        </span>
    </div>
</div>

我想要的结果:enter image description here

1 个答案:

答案 0 :(得分:1)

要更改查看模式,您只需使用viewMode选项。

您可以使用默认配置(天或月)初始化datepicker,然后使用viewModeformat函数更改选项。

您可以使用以下代码作为示例:

&#13;
&#13;
// Init datetimepicker with default config
// (if you want date config change format: 'DD-MM-YYYY' and viewMode: 'days')
var picker = $('#datetimepicker3').datetimepicker({
  format: 'M-YYYY',
  maxDate: 'now',
  viewMode: 'months'
});

$("#Month").click(function () {
  picker.data("DateTimePicker").format('M-YYYY');
  picker.data("DateTimePicker").viewMode('months');

});
$("#Date").click(function () {
  picker.data("DateTimePicker").format('DD-MM-YYYY');
  picker.data("DateTimePicker").viewMode('days');

});
&#13;
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.css" rel="stylesheet"/>
<link href="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.6.3/css/font-awesome.css" rel="stylesheet"/>

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

<div class="form-group">
  <div class="input-group date" id="datetimepicker3">
    <input type="text" class="form-control" />
    <span class="input-group-addon"><span class="glyphicon glyphicon-time"></span></span>
  </div>
</div>
<div class="form-group">
  <button id="Month" class="btn btn-default">Month</button>
  <button id="Date" class="btn btn-default">Date</button>
</div>
&#13;
&#13;
&#13;