How do I get Date Range Picker selected date to a variable? - javascript

hi i am using data range picker for filter option. there is change with default date picker range is . here i am using a div instead of text box. so tthat i need the selected start date and end date in a variable how can i due it?. i try like this way...
$('#Date').daterangepicker();
$(document).on("click",".applyBtn",function() {
// var range = $('#Date').datarangepicker.getRange();
// var startDate = range.start;
// var endDate = range.end;
var x =$('#Date').data('daterangepicker').StartDate()
alert(x);
});
<!-- 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" />
<div id="Date" class="col-xs-5 col-md-4 paddingNull filterImageAlign" >here select</div>

Try this.
var startDate = $('#Date').data('daterangepicker').startDate._d;
var endDate = $('#Date').data('daterangepicker').endDate._d;

If you need to get it formatted locally
$('#Date').daterangepicker().on('apply.daterangepicker', function (e, picker) {
var startDate = picker.startDate.format('DD-MM-YYYY');
var endDate = picker.endDate.format('HH:mm');
})

Related

Setting local storage for Datepicker

I have a J query code which shows the date picker
<!doctype html>
<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="/resources/demos/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() {
$( "#datepicker" ).datepicker();
} );
</script>
</head>
<body>
<div id = "date">
<p>Date: <input type="text" id="datepicker"></p>
</div>
</body>
</html>
I have tried local storage to save the date inside the textfield, but it seems to erase on page refresh. Please help. Thanks a lot for your time.
My local storage code
<script type="text/javascript">
document.getElementById("datepicker").value = getSavedValue("datepicker"); // set the value to this input
/* Here you can add more inputs to set value. if it's saved */
//Save the value function - save it to localStorage as (ID, VALUE)
function saveValue(e){
var id = e.id; // get the sender's id to save it .
var val = e.value; // get the value.
localStorage.setItem(id, val);// Every time user writing something, the localStorage's value will override .
}
//get the saved value function - return the value of "v" from localStorage.
function getSavedValue (v){
if (!localStorage.getItem(v)) {
return "";// You can change this to your defualt value.
}
return localStorage.getItem(v);
}
</script>
Check the below snippet to store and update data with localStorage
Update localStorage with the selected date when datepicker is closed, with onClose event
Set back the date from localStorage to datepicker on load of the document
Note: Snippet is throwing an error as localStorage is not accessible within the below sandbox.
var storage = {
saveDate: function (dateText, instance) {
// If not valid date take last selected value
var validDateText = dateText ? (dateText.match(/\d{2}\/\d{2}\/\d{4}/) || [instance.lastVal])[0] : "";
var data = JSON.parse(localStorage.getItem('jq-ui-datepicker') || "{}");
data[instance.id] = validDateText;
localStorage.setItem('jq-ui-datepicker', JSON.stringify(data));
instance.input.val(validDateText);
},
getDate: function () {
var data = JSON.parse(localStorage.getItem('jq-ui-datepicker') || "{}");
$(".datepicker").each(function () {
var $this = $(this),
dateText = data[$this.attr('id')];
if (dateText) {
// Set date to datepicker
$this.datepicker('setDate', dateText);
}
})
}
}
$(function () {
$(".datepicker").datepicker({
onClose: storage.saveDate
});
storage.getDate();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"
integrity="sha512-uto9mlQzrs59VwILcLiRYeLKPPbS/bT71da/OEBYEwcdNUk8jYIy+D176RYoop1Da+f9mvkYrmj5MCLZWEtQuA=="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css"
integrity="sha512-aOG0c6nPNzGk+5zjwyJaoRUgCdOrfSDhmMID2u4+OIslr0GjpLKo7Xm0Ao3xmpM4T8AmIouRkqwj1nrdVsLKEQ=="
crossorigin="anonymous" />
<div id="date">
<p>Date - 1: <input type="text" id="date1" class="datepicker"></p>
<p>Date - 2: <input type="text" id="date2" class="datepicker"></p>
</div>

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" />

Amsul DateTimePicker - How to unselect active date?

I am using amsul DateTime picker (https://amsul.ca/pickadate.js/date/) where if you see in the preview the today's date is highlighted in green. Now if you move the calendar to the next month or previous month. Every month's today's date is also highlighted.
How do I unhighlight any other dates then today's date?
$('.datepicker').pickadate()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://hateable-tests.000webhostapp.com/classic.css" rel="stylesheet">
<link href="https://hateable-tests.000webhostapp.com/classic.date.css" rel="stylesheet">
<link href="https://hateable-tests.000webhostapp.com/classic.time.css" rel="stylesheet">
<script src="https://hateable-tests.000webhostapp.com/picker.js"></script>
<script src="https://hateable-tests.000webhostapp.com/legacy.js"></script>
<script src="https://hateable-tests.000webhostapp.com/picker.date.js"></script>
<script src="https://hateable-tests.000webhostapp.com/picker.time.js"></script>
<input type="text" class="datepicker">
I belive this is the answer:
https://github.com/amsul/pickadate.js/issues/805
ilnee commented on 2 Oct 2016
I ran into this issue as well. As a workaround, I remove the
picker__day--highlighted class from every div with that class that
doesn't have today's timestamp as data-pick value:
var now = new Date();
var timestamp = new Date(now.getFullYear(), now.getMonth(), now.getDate()) / 1;
$('.datepicker').pickadate({
onRender: function() {
$('div.picker__day--highlighted').each(function(index, value) {
if ($(this).data('pick') !== timestamp) {
$(this).removeClass('picker__day--highlighted');
}
});
}
});

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.

Disable some future dates in DateRangePicker

I'm trying to disable today date and 6 more days dates from today.
I know I can do that with maxDate but when I do, it disable all future dates.
My code:
$('input[name="datefilter"]').daterangepicker({
autoUpdateInput: false,
maxDate: new Date(),
"autoApply": true,
locale: {
"firstDay": 1,
"separator": " - "
}
});
I tried with maxDate: new Date(6) too but same error.
Any idea?
You can use the isInvalidDate function to return true/false if the date is valid or not:
invalid_dates = ['2017-01-11', '2017-01-12', '2017-01-13']
$(function() {
$('input[name="daterange"]').daterangepicker({
isInvalidDate: function(date)
{
return !!(invalid_dates.indexOf(date.format('YYYY-MM-DD')) > -1);
}
});
});
<!-- 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" />
<input type="text" name="daterange" value="01/01/2017 - 01/10/2017" />
That's not an error, that's the expected behavior of the property you're using. You're telling it "don't allow any date beyond this". According to the docs, there is an option for isInvalidDate that Dekel found in his answer.
I was about to delete this answer, but decided against it due to pointing out that it wasn't an error, but the behavior of the property that was being used. Anyone should definitely upvote the other answer for finding that property first.

Categories