Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS error when initializing bootstrap datetimepicker if input value contains only time

I'm using DateTime Picker and I want to load a only Time picker.

I initialize my input field like this and works good. This let me pick only times jsfiddle:

<div class="input-group date" id="datetimepicker_hour1">
  <input type="text" id="hour_from" name="hour_from" class="form-control" />
</div>
$('#datetimepicker_hour1').datetimepicker({
  language: 'es',
  format: 'hh:ii',
  minuteStep: 60,
  autoclose: true,
  minView: 1,
  maxView: 1,
  startView: 1
});

If I want initialize this input with a time preselected, JS error occurs:

"Uncaught TypeError: Cannot read property 'getTime' of undefined"

But if I put the input value like this 2017-12-24 13:00, the input time picker have that full value. That works good, but I want that the first value could be only the time, not full datetime.

Here is jsfiddle with a value preloaded. I want that this value could be 13:00:

<div class="input-group date" id="datetimepicker_hour1">
  <input type="text" id="hour_from" name="hour_from" class="form-control" value="2017-12-24 13:00" />
</div>
$('#datetimepicker_hour1').datetimepicker({
  language: 'es',
  format: 'hh:ii',
  minuteStep: 60,
  autoclose: true,
  minView: 1,
  maxView: 1,
  startView: 1
});
like image 951
fcastillo Avatar asked Nov 12 '17 11:11

fcastillo


1 Answers

Let's do a little trick. First we'll hide the input field. Then we'll devide the datetime value by space character to get only the time and set this as the input value. After that we will show the input field.

var $hour_from = $("#hour_from");
$hour_from.datetimepicker({
  language: 'es',
  format: 'hh:ii',
  minuteStep: 60,
  autoclose: true,
  minView: 1,
  maxView: 1,
  startView: 1,
  timeFormat: 'hh:mm',

});
$hour_from.val($hour_from.val().split(' ')[1])
$hour_from.show();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://rawgit.com/AuspeXeu/bootstrap-datetimepicker/master/js/bootstrap-datetimepicker.js"></script>
<link href="https://rawgit.com/AuspeXeu/bootstrap-datetimepicker/master/css/bootstrap-datetimepicker.css" rel="stylesheet"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<div class="input-group date" id="datetimepicker_hour1">
  <input type="text" id="hour_from" name="hour_from" class="form-control" value="2017-12-24 13:00" data-date-format="hh:ii" style="display:none;" />
</div>
like image 135
camelsWriteInCamelCase Avatar answered Sep 23 '22 13:09

camelsWriteInCamelCase