Bootstrap datetimepicker select time view mode - javascript

Hi I'm working with bootstrap datetimepicker. I'm trying to show select time view after choose date (click on date). Is there any events to open select time view or something else?

If you are using eonasdan datetimepicker you may use the following events:
dpchange in order to test if the user changed the date
click in order to reset the datetimepicker to the default condition (no time selection)
The snippet:
$('#datetimepicker1').datetimepicker().on('dp.change', function(e) {
var currDate = e.date.format('DD/MM/YYYY');
var oldDate = (e.oldDate == null) ? currDate : e.oldDate.format('DD/MM/YYYY');
var sideBySide = $('#datetimepicker1').data("DateTimePicker").options().sideBySide;
if (currDate != oldDate && sideBySide == false) {
$('#datetimepicker1').data("DateTimePicker").sideBySide(true);
}
}).on('click', 'span.input-group-addon', function(e) {
$('#datetimepicker1').data("DateTimePicker").sideBySide(false);
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>
<link rel="stylesheet" href="https://rawgit.com/Eonasdan/bootstrap-datetimepicker/master/build/css/bootstrap-datetimepicker.min.css">
<script src="https://rawgit.com/Eonasdan/bootstrap-datetimepicker/master/build/js/bootstrap-datetimepicker.min.js"></script>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>

Related

Getting instance and field id of jQuery Datepicker

I've found a bunch of similar questions for this issue but none of their answers seems to work here. I have a Datepicker in a website where the input of a date is checked when the user is typing. It works well but I also want to have the date colored in realtime when the input is not valid. For that I need the id of the input field the Datepicker is associated with.
When using onClose function in Datepicker definiton, I get inst which is the instance of the current Datepicker object and by inst.id I get the field name. But this does not work in the parseDate function. I also can't pass on inst or make it global, because onClose is never executed before parseDate. I tried $(this).attr('id') as suggested somewhere but it returns undefined. My code (minimal example):
document.addEventListener("DOMContentLoaded", function () {
$(function () {
$(".dp").datepicker({
showOn: "focus",
showMonthAfterYear: false,
dateFormat: "dd.mm.yy",
onClose: function (dateText, inst) {
console.log("field name : ", inst.id); //works, inst.id is 'startDate'.
$("#" + inst.id + ".form-control.dp.hasDatepicker").css("color", "red"); //works, inst.id is 'startDate'.
}
});
$.datepicker.parseDate = function (format, value, settings) {
var field = $(this).attr("id"); //not working, field is null.
$("#" + field + ".form-control.dp.hasDatepicker").css("color", "red"); //not working, field is null.
};
});
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="row">
<label class="col-sm-3 col-form-label">{{ __('Start') }}</label>
<div class="col-sm-9">
<div class="input-group-addon">
<input type="text" class="form-control dp" id="startDate" name="start" value="">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
I would perform the date validity with a input event handler aside the date picker... Because that date check you wish to have is not a feature of datepicker.
So on input, evaluate the new Date value to add an .invalid class to the input like below:
$(document).ready(function () {
$(".dp").datepicker({
showOn: "focus",
showMonthAfterYear: false,
dateFormat: "dd.mm.yy"
});
$(".dp").on("input", function () {
// Remove the class on each new input
$(this).removeClass("invalid");
let currentVal = $(this).val();
console.log(currentVal);
// Split the value
let dateParts = currentVal.split(".");
// If incomplete
if (dateParts.length !== 3) {
$(this).addClass("invalid");
return;
}
// Create a date object to evaluate
let validDate = new Date(`${dateParts[2]}-${dateParts[1]}-${dateParts[0]} 00:00:00`);
console.log(validDate.toString());
// If the date is "invalid" and does not have 4 digits for the year (because it could be valid anyway... But obviously wrong)
if (validDate.toString() === "Invalid Date" || dateParts[2].length !== 4) {
$(this).addClass("invalid");
}
});
});
.dp.invalid{
color: red !important;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="row">
<label class="col-sm-3 col-form-label">{{ __('Start') }}</label>
<div class="col-sm-9">
<div class="input-group-addon">
<input type="text" class="form-control dp" id="startDate" name="start" value="">
<span class="glyphicon glyphicon-th"></span>
</div>
</div>
</div>
CodePen

Knockout binding to a date picker

I'm trying to pass the selected date from a Bootstrap date picker to Javascript code. Plus by default, the date picker should select today's date.
Currently, when clicking the search button, the current date is shown in the alert. However, I'm having trouble actually binding it to the date picker. What am I missing/doing wrong?
Date picker code:
<form class="form form-horizontal" style="background-color:white">
<div class="form-group">
<div class="col-lg-2">
<div class="input-group addon">
<span class="input-group-addon"><i class="fa fa-calendar"></i></span>
<input id="searchDate" readonly style="cursor: pointer;" data-bind="datePicker: SearchDate" class="form-control pad-bottom-when-small" type="text" data-provide="datepicker" data-date-format="dd/mm/yyyy" data-date-autoclose="true"/>
</div>
</div>
<div class="col-lg-3">
<button class="btn btn-success" onclick="search()">Search</button>
</div>
</div>
</form>
My attempt to data bind:
<script>
ko.applyBindings({
SearchDate: ko.observable(moment().toDate()),
});
</script>
<script type="text/javascript">
self.SearchDate = ko.observable(moment().toDate());
function search() {
alert(self.SearchDate());
}
</script>
It seems that you require some reading up on the knockout-side, specifically on the custom binding handler section, it is -a- way of hooking up non-knockout code with your knockout viewmodel in a clean manner. This also creates a reusable piece of code should you need the calendar picker in another part of your application. I've created a very basic concept of what you will require, as an exercise I'll let you sort out the error-handling when entering false dates, or maybe try to come up with an idea where you could implement the addition of having an empty/null input box.
ko.bindingHandlers.datePicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
var options = { format: 'dd-mm-yyyy', weekStart: 1, autoclose: true };
$(element).datepicker(options);
$(element).datepicker().on('changeDate', function(e) { valueAccessor()(e.date); });
},
update: function(element, valueAccessor, allBindingsAccessor) {
var date = ko.unwrap(valueAccessor());
$(element).datepicker('setDate', date);
}
};
ko.applyBindings(() => {
var self = this;
self.foo = ko.observable(new Date());
self.bar = ko.computed(() => {
var date = self.foo();
return date.getDate() + '-' + (date.getMonth() + 1) + '-' + date.getFullYear();
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.3.1/js/bootstrap.min.js"></script>
<input type="text" data-bind="datePicker: foo" />
<div data-bind="text: bar"></div>

Updating minDate with dropdown on a bootstrap DateTimePicker

I have a date time picker in my project and need the min date to update whenever I select a different option on a drop down. Currently I have:
<div id="howManydays"></div>
<select id="ago">
<option value="7">week</option>
<option value="31">month</option>
<option value="365">year</option>
</select>
for my drop down and my date time picker is:
<div class='input-group date' id='startDateTimeDiv'>
<input id="startDateTimeSelection" type='text' class="form-control" name="startDateTimeSelection" style="width: 250px;" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
<!-- bootstrap date time pickers -->
<script type="text/javascript">
$(function() {
$('#startDateTimeDiv').datetimepicker({
format : 'YYYY-MM-DD HH:mm:ss',
minDate : moment().subtract(document.getElementById("ago").value, 'd').format( 'YYYY-MM-DD'),
maxDate : moment().add(1, 'd').format('YYYY-MM-DD'),
widgetPositioning :
{
horizontal : 'right',
vertical : 'bottom'
}
});
});
</script>
When I change the value of the drop down then the picker is still locked to the last 7 days. Any help appreciated.
If you are using boostrap 3 you can use .options():
$('#ago').selectpicker().on('change', function(e) {
var x = this.value;
$('#startDateTimeDiv').data("DateTimePicker").options({
minDate : moment().subtract(x, 'd'),
maxDate : moment().add(1, 'd')
});
});
Note: you don't need to use .format('YYYY-MM-DD') because you are using a moment object.
$('#ago').selectpicker().on('change', function(e) {
var x = this.value;
$('#startDateTimeDiv').data("DateTimePicker").options({
minDate : moment().subtract(x, 'd'),
maxDate : moment().add(1, 'd')
});
});
$('#startDateTimeDiv').datetimepicker({
format : 'YYYY-MM-DD HH:mm:ss',
minDate : moment().subtract(document.getElementById("ago").value, 'd'),
maxDate : moment().add(1, 'd'),
widgetPositioning :
{
horizontal : 'right',
vertical : 'bottom'
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/css/bootstrap-datetimepicker.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.47/js/bootstrap-datetimepicker.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
<div class="container">
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<select id="ago">
<option value="7">week</option>
<option value="31">month</option>
<option value="365">year</option>
</select>
</div>
</div>
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='startDateTimeDiv'>
<input type='text' class="form-control"/>
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
</div>
</div>

Keep value of date to a default one if no date is selected

I want to keep the value of a Date to a default value that I specified. If no date is selected when user click submit button.
what I need the functionality to be. If user select a date and submit the form, after submission the form selected date value must be the value on the date field which works perfectly so. I have the problem ie. when date is not selected and user submit form the date field have the today's date by default Select Date
My code is as follows
HTML
<body onload="CovertDateToString()">
<form action="searchDate" method="post" id="searchDate" class="searchDate" modelAttribute="searchDate">
<!-- Select type selectDateRange-->
<div class="form-group ">
<div class="col-md-3 selectContainer">
<div class="input-group">
<input type="text" class="form-control" name="selectDateRange" id="selectDateRange" value="${newDate}">
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
<!-- Select type search button with input-->
<div class="form-group">
<div class="col-md-3 inputGroupContainer">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-success" type="submit">
<div class="up" style="margin-top: -8%; color: white;">Search</div></button>
</span>
</div>
<!-- /input-group -->
</div>
</div>
</form>
</body>
Js code
function CovertDateToString() {
var date = <%=request.getParameter("selectDateRange")%>;
var myDate = new Date();
var selectDate = myDate.toDateString();
var selectDate = "Select Date";
document.getElementsByName('selectDateRange')[0].value = selectDate;
selectDate = date;
document.getElementsById('selectDateRange')[0].value = date;
console.log("Set Date to Select Date ",selectDate);
console.log("Set Date to Selected Date ",date);
}
daterangepicker
$(function() {
$('input[name="selectDateRange"]').daterangepicker({
locale: {
format: 'YYYY-MM-DD'
}
});
});
function CovertDateToString() {
var date = "${newDate}";
var myDate = new Date();
var selectDate = myDate.toDateString();
document.getElementsByName('selectDateRange')[0].value = selectDate;
selectDate = date;
document.getElementById('selectDateRange').value = date;
console.log("Set Date to Select Date ",selectedDate);
console.log("Set Date to Selected Date ",date);
}
$(function() {
$('input[name="selectDateRange"]').daterangepicker({
locale: {
format: 'YYYY-MM-DD'
}
});
});
After more hours on this issue I final got it to work. Removing the request.getParamter was the mean reason date got removed after
Please check the following code i have used static values at the place of dynamic values so manage it and code is working fine at snnipet.
function CovertDateToString() {
var date = "${newDate}";
var arr = date.split(" ");
if(arr != "null"){
$("#selectDateRange").data('daterangepicker').setStartDate(arr[0]);
$("#selectDateRange").data('daterangepicker').setEndDate(arr[2]);
}
}
$(function() {
$('input[name="selectDateRange"]').daterangepicker({
locale: {
format: 'YYYY-MM-DD'
}
});
});
<script src="https://cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" rel="stylesheet"/>
<body onload="CovertDateToString()">
<form action="searchDate" method="post" id="searchDate" class="searchDate" modelAttribute="searchDate">
<!-- Select type selectDateRange-->
<div class="form-group ">
<div class="col-md-3 selectContainer">
<div class="input-group">
<input type="text" class="form-control" name="selectDateRange" id="selectDateRange" >
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
</div>
</div>
</div>
<!-- Select type search button with input-->
<div class="form-group">
<div class="col-md-3 inputGroupContainer">
<div class="input-group">
<span class="input-group-btn">
<button class="btn btn-success" type="submit">
<div class="up" style="margin-top: -8%; color: white;">Search</div></button>
</span>
</div>
<!-- /input-group -->
</div>
</div>
</form>
</body>

Bootstrap date and time separately getting conflict

I had used the date picker and datetimepicker separately in my form. If I work only on time or date they are working. But when I put both the time is not working. Instead of time it's displaying the date.
My code is as follows :
<!DOCTYPE html>
<html>
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>
<div>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker3' style="width:140px;">
<input type="text" class="form-control">
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'LT'
});
});
</script>
</div>
</div>
</div>
<div class="container">
<div class="row">
</div>
<br />
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
var bindDatePicker = function () {
$(".date").datetimepicker({
format: 'YYYY-MM-DD',
icons: {
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-arrow-up",
down: "fa fa-arrow-down"
}
}).find('input:first').on("blur", function () {
// check if the date is correct. We can accept dd-mm-yyyy and yyyy-mm-dd.
// update the format if it's yyyy-mm-dd
var date = parseDate($(this).val());
if (!isValidDate(date)) {
//create date based on momentjs (we have that)
date = moment().format('YYYY-MM-DD');
}
$(this).val(date);
});
}
var isValidDate = function (value, format) {
format = format || false;
// lets parse the date to the best of our knowledge
if (format) {
value = parseDate(value);
}
var timestamp = Date.parse(value);
return isNaN(timestamp) == false;
}
var parseDate = function (value) {
var m = value.match(/^(\d{1,2})(\/|-)?(\d{1,2})(\/|-)?(\d{4})$/);
if (m)
value = m[5] + '-' + ("00" + m[3]).slice(-2) + '-' + ("00" + m[1]).slice(-2);
return value;
}
bindDatePicker();
});
</script>
</div>
</div>
Image reference for problem.
This will Resolve your problem
<div class="container">
<div class="row">
<div class='col-sm-6'>
<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>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'LT'
});
});
</script>
</div>
Just copy and paste I think this is what you need :)
I think you get date in both fields ?
You can now just copy and past
Just change the return variable names for Date Picker
From that it will interferer the stored variables of bootstrap time picker
<!DOCTYPE html>
<html>
<head>
<script
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js">
</script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/
bootstrap.min.css">
<script
src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js">
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-
datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
</head>
<body>
<div>
<div class="container">
<div class="row">
<div class='col-sm-6'>
<div class="form-group">
<div class='input-group date' id='datetimepicker3' style="width:140px;">
<input type="text" class="form-control">
<span class="input-group-addon">
<span class="glyphicon glyphicon-time"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
$('#datetimepicker3').datetimepicker({
format: 'LT'
});
});
</script>
</div>
</div>
</div>
<div class="container">
<div class="row">
</div>
<br />
<div class="row">
<div class='col-sm-3'>
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon"><span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
</div>
<script type="text/javascript">
$(function () {
var bindDatePicker = function () {
$(".date").datetimepicker({
format: 'YYYY-MM-DD',
icons: {
time: "fa fa-clock-o",
date: "fa fa-calendar",
up: "fa fa-arrow-up",
down: "fa fa-arrow-down"
}
}).find('input:first').on("blur", function () {
// check if the date is correct. We can accept dd-mm-yyyy and yyyy-mm-dd.
// update the format if it's yyyy-mm-dd
var date = parseDate($(this).val());
if (!isValidDate(date)) {
//create date based on momentjs (we have that)
date = moment().format('YYYY-MM-DD');
}
$(this).val(dates);
});
}
var isValidDate = function (value, format) {
format = format || false;
// lets parse the date to the best of our knowledge
if (format) {
value = parseDate(value);
}
var timestamp = Date.parse(value);
return isNaN(timestamp) == false;
}
var parseDate = function (value) {
var m = value.match(/^(\d{1,2})(\/|-)?(\d{1,2})(\/|-)?(\d{4})$/);
if (m)
values = m[5] + '-' + ("00" + m[3]).slice(-2) + '-' + ("00" + m[1]).slice(-2);
return values;
}
bindDatePicker();
});
</script>
</div>
</div>

Categories

Resources