Friday, October 11, 2019

How to add jQuery datetimepicker in the page?

Today we would be looking at the jQuery datetimepicker implementation. It improves the User Experience. One needs to make a few things in mind for datetimepicker integration like
  • Adding the required HTML code snippet in the page for selecting the date & time i.e. adding input element of type text  
  • Respective JS & CSS libraries(datetimepicker and jQuery related) should be included in the page
  • Activating the datetimepicker using jQuery or JavaScript 
After configuring the datetimepicker, it would look like below:


Implementation:


<html>
<head>
<title>Datetimepicker Demo</title>
<!–– Respective JS & CSS libraries(datetimepicker and jQuery related) should be included in the page ––>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.min.css" rel="stylesheet"/> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.20/jquery.datetimepicker.full.min.js"></script>
<script>
$(document).ready(function () {
   // Activating the datetimepicker using jQuery or JavaScript 
   $('#datetimepicker1').datetimepicker(); //default    
   $('#datetimepicker2').datetimepicker({ //customized
      format:'d/m/Y H:i',
      minDate:0,
      formatTime:"h:i a",
      step:10,
      // if one would like to take user selected input from datetimepicker and atomatically round off to nearest integral of 10 minutes
      onChangeDateTime:function(dp,$input){
      //27/10/2019 12:01 -> dateTime[0] = date, dateTime[1] = time
 var dateTime = $input.val().split(" "); 
 var time = dateTime[1].split(":");
 var hour = time[0];
 var minutes = time[1];
 var datetimestring;
    
 if(minutes > 0 && minutes < 10) {
         datetimestring = dateTime[0] + ' ' + hour + ':' + 10;
         $input.val(datetimestring);
  }
    ...
  } // end of onChangeDateTime function
   });
   
});
</script>
</head>
<body>
<!–– Adding the required HTML code snippet in the page for selecting the date & time i.e. adding input element of type text  ––>
Default Datetimepicker:
<input type="text" id="datetimepicker1" placeholder="select date time">
Customized Datetimepicker:
<input type="text" id="datetimepicker2" placeholder="select date time">
</body>
</html>

Hoping that it would help you. Happy Learning!! ☺

No comments:

Post a Comment