How to set date-picker with JQuery 3.3.1 and Bootstrap 3.3.7?

espresso_coffee picture espresso_coffee · May 31, 2018 · Viewed 17.5k times · Source

I have to set date picker for input fields in few different forms. In the past I have used jQuery date-picker but for this project I use Bootstrap 3 so there is another method that is available. Here is example that I have so far:

You can see that snippet above works but there is few things that I would like to modify. First I would like input field to be readonly. User should be able to click on calendar icon and then chose date only. I do not need time next to the date. Clicking on the icon will prevent user to enter what ever they want. I'm wondering if there is a way to achieve this with date-picker in bootstrap and jquery?

Answer

VincenzoC picture VincenzoC · Jun 1, 2018

You have to move datepick class from <input> to the <div> with the input-group class, to let the user open the picker clicking on the calendar icon.

Then you have to add readonly property to the input and set ignoreReadonly option to true.

Use format option to customize date format and to hide timepicker, as the docs says:

See momentjs' docs for valid formats. Format also dictates what components are shown, e.g. MM/dd/YYYY will not display the time picker.

Here a live sample:

$(document).ready(function() {
  $('.datepick').datetimepicker({
    format: 'L',
    ignoreReadonly: true
  });
});
<!---*** Start: JQuery 3.3.1 version. ***--->
<script language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!---*** End: JQuery 3.3.1 version. ***--->
<!---*** Start: Bootstrap 3.3.7 version files. ***--->
<script language="javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!---*** End: Bootstrap 3.3.7 version files. ***--->

<script language="javascript" src="https://momentjs.com/downloads/moment.js"></script>
<script language="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css">

<div class="form-group required">
  <div class="input-group datepick">
    <input type="text" class="form-control" name="frmSaveOffice_startdt" id="frmSaveOffice_startdt" required readonly>
    <div class="input-group-addon">
      <span class="glyphicon glyphicon-calendar"></span>
    </div>
  </div>
</div>