Display specific dates in bootstrap datepicker - javascript

I'm using bootstrap date picker in my project. It's a session booking project. From the admin panel, I add the sessions for specific dates and I want the user's of my website to be able to see the dates for which I have added a session. My frontend receives the data from database. The data contains all the dates for which I have added a session. I want my datepicker to display only these dates from the data and disable the other dates.
Currently I have temporarily used a select box to solve this issue. But a datepicker would be better as it looks good is easy to navigate.
See the picture below. This is how I have used a select box to temporarily solve the problem
Here is the desired output that I want
It should be a datepicker with only those dates enabled which I receive from the database. The other dates should be disabled
I tried searching it on google but I'm not able to find the solution. Is this possible using bootstrap date picker? If yes, please suggest a workaround.

You can use beforeShowDay function to enable only the dates returned from your back end system.
Documentation here
This function is executed for every date, it checks if it is present in the list of applicable dates, returns true if present and enables it, else returns false and disables it.
$(function () {
let enabledDates = ['2018-10-03', '2018-10-04', '2018-10-05', '2018-10-06', '2018-10-07', '2018-10-08'];
$('#datepicker').datepicker({
format: 'yyyy-mm-dd',
beforeShowDay: function (date) {
let fullDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
return enabledDates.indexOf(fullDate) != -1
}
});
});
beforeShowDay function also allows you to return classes for custom styling
beforeShowDay: function (date) {
let fullDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
if (enabledDates.indexOf(fullDate) != -1) {
return {
classes: 'enabled',
tooltip: 'You can select this date'
};
} else
return false
}
.enabled {
background: #DCDCDC;
}

None of the other solutions worked for me so here is my solution.
The documentation is not so clear and lacks of example but you can see a function that takes a date as a parameter and returns a Boolean, indicating whether or not this date is selectable
In this snippet, look at January 2020 for example in order to see only the active dates.
$(document).ready(function() {
var datesEnabled = [
'2021-01-01', '2021-01-11', '2021-01-21',
'2021-02-01', '2021-02-11', '2021-02-21',
'2021-03-01', '2021-03-11', '2021-03-21',
'2021-04-01', '2021-04-11', '2021-04-21',
'2021-05-01', '2021-05-11', '2021-05-21'
];
$("#datepicker-lorem").datepicker({
language: "fr",
autoclose: true,
todayHighlight: true,
todayBtn: true,
title: 'Test ;-)',
weekStart: 1,
format: 'dd/mm/yyyy',
// On n'active que les dates possibles
beforeShowDay: function(date) {
var allDates = date.getFullYear() + "-" + ('0' + (date.getMonth() + 1)).slice(-2) + "-" + ('0' + date.getDate()).slice(-2);
if (datesEnabled.indexOf(allDates) != -1) {
return {
classes: 'date-possible',
tooltip: 'Vous pouvez choisir cette date'
}
} else {
return false;
}
}
});
});
/* For better frontend result, add class to active date and add opacity to disabled date */
td.day.disabled {
opacity: 0.4;
}
td.date-possible {
background-color: red;
color: white;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.3/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/css/bootstrap-datepicker.min.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/twitter-bootstrap/4.5.3/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.fr.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.9.0/js/bootstrap-datepicker.min.js"></script>
<div class="container">
<div class="row">
<div class="col">
<input class="form-text form-control" type="text" id="datepicker-lorem" name="date_demande" value="" size="60" maxlength="128">
</div>
</div>
</div>

Using 'beforeShowDay' parameter you can disable dates:
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="//jqueryui.com/jquery-wp-content/themes/jqueryui.com/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$(function() {
//date list that you want to disable
disableddates = ['10-10-2018', '10-11-2018', '10-12-2018'];
$("#datepicker").datepicker({
format: 'dd-mm-yyyy',
beforeShowDay: function(date) {
var m = date.getMonth();
var d = date.getDate();
var y = date.getFullYear();
var currentdate = (m + 1) + '-' + d + '-' + y;
for (var i = 0; i < disableddates.length; i++) {
// Now check if the current date is in disabled dates array.
if ($.inArray(currentdate, disableddates) != -1) {
return [false];
}
}
return [true];
},
autoclose: 1,
todayHighlight: 1,
startView: 2,
minView: 2,
});
});
</script>
</head>
<body>
<p>Date:
<input type="text" id="datepicker">
</p>
</body>
</html>
</body>
</html>

Related

Make Datepicker appear when clicking on field in Qualtics

I'm trying to combine two pieces of code. I like the Google data picker style and I like the code that makes it appear when you click on the specific question.
Below are the two pieces of code. I know it's something to do with the function hideFixFuntion but my lack of JavaScript knowledge is stopping me figuring it out. Please could someone help make the google datepicker code appear and disappear when you click on Question QID27?
Many thanks
Rodp
Google datepicker code
Qualtrics.SurveyEngine.addOnload(function()
{
var qid = this.questionId;
var calid = qid + '_cal';
var y = QBuilder('div');
$(y).setStyle({clear:'both'});
var d = QBuilder('div',{className:'yui-skin-sam'},[
QBuilder('div', {id:calid}),
y
]);
var c = this.questionContainer;
c = $(c).down('.QuestionText');
c.appendChild(d);
var cal1 = new YAHOO.widget.Calendar(calid);
cal1.render();
var input = $('QR~' + qid);
$(input).setStyle({marginTop: '20px',width: '150px'});
var p =$(input).up();
var x = QBuilder('div');
$(x).setStyle({clear:'both'});
p.insert(x,{position:'before'});
cal1.selectEvent.subscribe(function(e,dates){
var date = dates[0][0];
if (date[1] < 10)
date[1] = '0' + date[1];
if (date[2] < 10)
date[2] = '0' + date[2];
input.value = date[0] +'-'+date[1]+'-'+date[2];
/* var dt = [ //this code was thought to be needed to reverse the date format but no longer reqiured. It's not quite working as it's not updating the field through the input.value method so something isn't quite right in the syntax
date.getFullYear(),
('0' + (date.getMonth() + 1)).slice(-2),
('0' + date.getDate()).slice(-2)
].join('-');
input.value = dt; */
})
});
For completion the above needs the following references in the Look and Feel header
<link href="https://ajax.googleapis.com/ajax/libs/yui/2.9.0/build/calendar/assets/skins/sam/calendar.css" rel="stylesheet" type="text/css" /><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/yui/2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script><script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/yui/2.9.0/build/calendar/calendar-min.js"></script>
below is the cdn.jsdelivr.net date picker code with the ability to make it visible when you click on the date field, sourced from: Utilizing Date Range Picker for Qualtrics date selection. It's the addeventlisterner and the hidefixfuntion() coding that I need help with transplanting into the above code. Note: the date picker isn't bringing up valid dates in the date picker for some reason but I'm not worried about that as the Google one above works fine.
Qualtrics.SurveyEngine.addOnload(function()
{
$('input[name="QR~QID27~TEXT"]').daterangepicker({
singleDatePicker: true,
autoUpdateInput: false,
locale: {
cancelLabel: 'Clear'
}
});
var x = document.getElementById('QR~QID27');
x.addEventListener('focusout', hideFixFunction);
function hideFixFunction() {
document.getElementById('QR~QID27').style.display = "inline-block";
}
$('input[name="QR~QID27~TEXT"]').on('apply.daterangepicker', function(ev, picker) {
$(this).val(picker.startDate.format('MM/DD/YYYY'));
document.getElementById('QR~QID27').style.display = "inline-block";
});
$('input[name="QR~QID27~TEXT"]').on('cancel.daterangepicker', function(ev, picker) {
$(this).val('');
document.getElementById('QR~QID27').style.display = "inline-block";
});
});
For completion the above needs the following references in the Look and Feel header
<!-- Include Required Prerequisites -->
<script type="text/javascript" src="//cdn.jsdelivr.net/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />
<!-- Include Date Range Picker -->
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />

jQuery - Get values from jQuery array got from field

First I have one field with daterangepicker.
I get value using $("#field").val().
I got like
{"start":"2018-03-23","end":"2018-03-29"}
But, I need start date and end date value from
{"start":"2018-03-23","end":"2018-03-29"}
My code is
<input id="field" type="text" value='' /><br/>
$(function() {
'use strict';
$("#field").daterangepicker({
dateFormat:'dd M',
datepickerOptions : {
numberOfMonths : 2
}
});
var curnt = moment().startOf('day').toDate();
var weeks = moment().subtract('days', 6).startOf('day').toDate();
$("#field").daterangepicker("setRange", {start: weeks, end: curnt});
});
function get_graph_data(){
var dates = JSON.parse($("#field").val());
console.log(dates.start);
console.log(dates.end);
var data = {
'action' : 'example_ajax_request',
'wp_graph': $("#field").val()
};
jQuery.post(ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
}
What you get from the $("#field").val() is a JSON. You can easily do something like:
var dates = JSON.parse($("#field").val());
dates.start; // "2018-03-23"
dates.end; // "2018-03-29"
A snippet to help you:
$(function () {
var dates = JSON.parse($("#field").val());
console.log(dates.start); // "2018-03-23"
console.log(dates.end); // "2018-03-29"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="field" type="hidden" value='{"start":"2018-03-23","end":"2018-03-29"}' />
You are using daterangepicker plugin so you should use it's methods instead of jQuery's val(). Select an input field and call data('daterangepicker'). Returned object contains startDate and endDate objects. Keep in mind that they are Date objects (not Strings), so you will need to format if you want to print them.
$('#field').daterangepicker({
locale: {
format: 'YYYY-MM-DD'
},
startDate: '2018-01-01',
endDate: '2018-12-31'
});
$("#getDateRange").click(function() {
var data = $("#field").data('daterangepicker');
var startDate = data.startDate.format('YYYY-MM-DD');
var endDate = data.endDate.format('YYYY-MM-DD');
alert('Start date: ' + startDate + ', end date: ' + endDate);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//cdn.jsdelivr.net/momentjs/latest/moment.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap/3/css/bootstrap.css" />
<script type="text/javascript" src="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.jsdelivr.net/bootstrap.daterangepicker/2/daterangepicker.css" />
<input id="field" type="text" value='' />
<button type="button" id="getDateRange">Get start date</button>
It's always a good habit to check out official documentation of a plugin. You can check it out here.

Semantic UI Calendar not showing

I'm trying experiment with Semantic UI Calendar where you have a date input field and a calendar pops up when you select it as shown in this first example. I'm unfamiliar with this process so I'm unsure if I'm properly linking the .js file or if it's something else. I've looked at other problems and saw mention of jquery, but again unsure about how to even check if that's the problem.
TOOLS:
Webstorm, Node.js
PROCESS:
1: npm install --save semantic-ui-calendar (install instructions ref)
2: Added the below code and tried to link them together
3: npm start (running on local host)
4: Page loads, input field and everything else wdisplays, calendar failing to show
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="/node_modules/semantic-ui-calendar/dist/calendar.min.js"></script>
<link rel="stylesheet" href="/node_modules/semantic-ui-calendar/dist/calendar.min.css" />
<script src="/utils/calendar.js"></script>
</head>
<body>
<div>
<div class="ui calendar" id="example1">
<div class="ui input left icon">
<i class="calendar icon"></i>
<input type="text" placeholder="Date/Time">
</div>
</div>
</div>
</body>
</html>
Javascript file:
$('#example1').calendar();
$('#example2').calendar({
type: 'date'
});
$('#example3').calendar({
type: 'time'
});
$('#rangestart').calendar({
type: 'date',
endCalendar: $('#rangeend')
});
$('#rangeend').calendar({
type: 'date',
startCalendar: $('#rangestart')
});
$('#example4').calendar({
startMode: 'year'
});
$('#example5').calendar();
$('#example6').calendar({
ampm: false,
type: 'time'
});
$('#example7').calendar({
type: 'month'
});
$('#example8').calendar({
type: 'year'
});
$('#example9').calendar();
$('#example10').calendar({
on: 'hover'
});
var today = new Date();
$('#example11').calendar({
minDate: new Date(today.getFullYear(), today.getMonth(), today.getDate() - 5),
maxDate: new Date(today.getFullYear(), today.getMonth(), today.getDate() + 5)
});
$('#example12').calendar({
monthFirst: false
});
$('#example13').calendar({
monthFirst: false,
formatter: {
date: function (date, settings) {
if (!date) return '';
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
return day + '/' + month + '/' + year;
}
}
});
$('#example14').calendar({
inline: true
});
$('#example15').calendar();
I think it doesn't works because you forget to import Jquery plugin, you can do it with a cdn :
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
And your javascript files is not good if you use Jquery, you have to start the files by :
$(document).ready(function() {
/* YOUR JAVASCRIPT CODE INSIDE */
});
Peace
It will not work because Semantic UI v2.3.3 does not provide a calendar function. You can check in the inspect section; it will throw an error. If you want to use calendar you need to downgrade your semantic.js file to v2.1.4.

Capturing a value in a jQuery UI datepicker and alerting it back to the user

I need your help.
How can some functionality be added onto the existing code below such that it will make the options below possible:
If the date1 field is blank and the user selects a date, an alert message will popup and say "User has selected [date]"
If the date1 field is not blank and the user selects a new date, an alert message will popup and say "User has change [old_date_value] to [new_date_value]
I am entirely new to jQuery, so go easy while criticizing me =\
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<style type="text/css">
</style>
<script type="text/javascript">
window.onload = function() {
$("#date1").datepicker({
changeMonth: true,
changeYear: true
});
}
</script>
</head>
<body>
<input type="text" id="date1">
</body>
</html>
Change the datepicker part of code to this:
var prevDate = null;
$("#date1").datepicker({
changeMonth: true,
changeYear: true,
onSelect: function(date) {
if (prevDate === null) {
alert('User has selected ' + date);
} else {
alert('User has change ' + prevDate + ' to ' + date);
}
prevDate = date;
}
});
You can find a suitable place to put the prevDate.
Also jQuery-datepicker would help you a lot.
You'll want to use the onSelect option which is part of the datepicker. The onSelect function has two parameters, the dateText, which is the date string, and the datepicker instance. You can get the last value from the datepicker instance, as lastVal.
Using the above information, your javascript would look like this:
$("#date1").datepicker({
changeMonth: true,
changeYear: true,
onSelect: function(dateText,inst) {
if(dateText !== inst.lastVal){
if (inst.lastVal == null) {
alert("User has selected: "+dateText);
} else {
alert("User has change "+inst.lastVal+" to "+dateText)
}
}
}
});
With this solution, you do not need to manage the previous date value in a variable, which is nice.
I've replicated your setup in jsFiddle so you can play around with this while you get used to jQuery.

Check Date greater than 30 days from today's date

I am using jQuery datepicker and tried to find out difference between todays date and selected date , but getting issues... rather than issues... I was not able to find it perfectly...
I tried to do this on 'onSelect event of datepicker '
Question:
How to check whether selected Date using jQuery Datepicjer is greater than 30 days from todays date ?
Any help will be appreciated....!!
note: dont want to use any libraries, I need to solve this by using only jQuery.
Get the timestamp for 30 days from now:
var timestamp = new Date().getTime() + (30 * 24 * 60 * 60 * 1000)
// day hour min sec msec
Compare that timestamp with the timestamp for the selected date.
if (timestamp > selectedTimestamp) {
// The selected time is less than 30 days from now
}
else if (timestamp < selectedTimestamp) {
// The selected time is more than 30 days from now
}
else {
// -Exact- same timestamps.
}
I have created one sample for you.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<script>
$(function() {
$( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
Date: <input type="text" id="thedate"/>
<div id="checkDate">Check Date</div>
</body>
</html>
and Js
$('#thedate').datepicker();
$('#checkDate').bind('click', function() {
var selectedDate = $('#thedate').datepicker('getDate');
var today = new Date();
var targetDate= new Date();
targetDate.setDate(today.getDate()+ 30);
targetDate.setHours(0);
targetDate.setMinutes(0);
targetDate.setSeconds(0);
if (Date.parse(targetDate ) >Date.parse(selectedDate)) {
alert('Within Date limits');
} else {
alert('not Within Date limits');
}
});
You can check this code online Here
Try this:
$('input').datepicker({
onSelect: function()
{
var date = $(this).datepicker('getDate');
var today = new Date();
if((new Date(today.getFullYear(), today.getMonth(), today.getDate()+30))>date)
{
//Do somthing here..
}
},
});
demo: http://jsfiddle.net/jeY7S/

Categories