Bootstrap datepicker选项不起作用

时间:2017-09-11 23:07:22

标签: jquery twitter-bootstrap bootstrap-datepicker

我有一个表单字段是一个日期,我使用了datepicker。这是表单字段:

<div class=form-group>
  <div class="input-group date" data-provide="datepicker">
    <input class="form-control" id="data" name="data" placeholder="VVVV/MM/DD" type="text" />
    <div class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </div>
  </div>
</div>

这些是我提供的未应用的选项:

$('#data').datepicker({
  format: "yyyy/mm/dd",
  todayHighlight: true,
  autoclose: true,
  clearBtn: true
});

此jQuery代码位于外部JavaScript文件中的$(document).ready()函数内,该文件包含在结束</body>标记之前。

2 个答案:

答案 0 :(得分:2)

在您的JQuery中,您定位的是<input/>元素的ID。如果您定位输入的父元素,则引导日期选择器将起作用。

尝试运行此代码段或查看 CodePen Demo

&#13;
&#13;
$(document).ready(function() {
  $("#datepicker-group").datepicker({
    format: "yyyy/mm/dd",
    todayHighlight: true,
    autoclose: true,
    clearBtn: true
  });
});
&#13;
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/css/datepicker.css" rel="stylesheet" />

<div class="form-group">
  <div id="datepicker-group" class="input-group date" data-date-format="mm-dd-yyyy">
    <input class="form-control" name="data" type="text" placeholder="YYYY/MM/DD" />
    <span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
  </div>
</div>


<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.3.0/js/bootstrap-datepicker.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

要克服这种情况,您需要使用

   $(document).ready(function () {      });

您需要定位输入的父元素。这样可以使日期选择器正常工作。

JS编码,

 <script>

        $(document).ready(function () {
            $('#selectDate').datepicker({
                dateFormat: 'dd/mm/yy', // set date format as you prefer
                changeMonth: true, // if you want to change months
                changeYear: true,  // if you want to change years
                yearRange: "-50:+10",
                clickInput: true,

                onSelect: function (date) {
                    $('#selectName').val(date).attr('readonly', true); // if you want to make event fire after the date selection
                }

            });
        });

    </script>