Get selected date before onChange event using flatpickr - javascript

I currently have a start date and end date date picker which gets pre-populated with dates on page load. If the user clicks the next button with out interacting with the date picker I cannot get the correct date thats in the picker and only the date as a string.
I can however retrieve the date from the onChange event but this could be to late in some instances.
Here is an example of my code to explain more:
startDateAccomm = flatpickr("#StartDate", {
minDate: instance.selectedDates[0],
dateFormat: dateFormat,
onChange: function (selectedDates, dateStr, instance) {
if (selectedDates.length > 0) {
endDateAccomm.config.minDate = selectedDates[0];
if (startDateAccomm.selectedDates.length > 0) {
startDateSelected = startDateAccomm.selectedDates[0].getFullYear() + "-" + (startDateAccomm.selectedDates[0].getMonth() + 1) + "-" + startDateAccomm.selectedDates[0].getDate();
}
if (endDateAccomm.selectedDates.length > 0) {
endDateSelected = endDateAccomm.selectedDates[0].getFullYear() + "-" + (endDateAccomm.selectedDates[0].getMonth() + 1) + "-" + endDateAccomm.selectedDates[0].getDate();
}
}
if () {
//do something here.
}
}
I want to set the min date to the date thats prepopulated on page load but cannot get in the correct format as instance is not defined until the date picker is interacted with.
Any help is greatly appreciated.

After trying out the various events and hooks provided by flatpickr https://flatpickr.js.org/events/#hooks I was able to use the onReady event.
onReady: function (selectedDates, dateStr, instance) {
startDateSelected = selectedDates[0].getFullYear() + "-" +
(selectedDates[0].getMonth() + 1) + "-" + selectedDates[0].getDate();
},

Related

Pure JavaScript Datepicker displays calendar only once to never do it again in a Shopify cart page

To achieve greater performance with our Shopify store, we decided to minimize use of jQuery across the site. In cartpage, I added a pure JavaScript datepicker that sometimes displays the calendar just once and never afterwards. I ensured only one version of jQuery loads in the theme, thinking multiple instances from other Shopify apps might be causing this issue. But even with a single jQuery instance being loaded now in the theme, the issue still persists. I don't see any console errors. Please add a product to the cart and go to the cart page to see this issue by clicking the date picker. Below is the link to the preview theme.
Following is the datepicker code for pickaday plugin.
<div class="cart-attribute__field">
<p>
<label for="ship_date">Ordering early? Pick a future ship date here:</label>
<input id="ship_date" type="text" name="attributes[ship_date]" value="{{ cart.attributes.ship_date }}" />
</p>
</div>
<p class="shipping-text">If you are placing an order with <b>a future ship date</b> that <u>also</u> includes multiple addresses please email support#packedwithpurpose.gifts upon placing your order to confirm your preferred ship date.</p>
<!-- Added 11162020 -->
<p class="shipping-text">Please note that specifying a date above ensures your gift is packaged and shipped on that date. <b>This is not a delivery date.</b> As we work with third party shipping agencies, your delivery date is subject to the specific carrier selected as well as your shipping destination. Please find our estimated shipping transit times for all regions of the US <strong>here</strong>.</p>
<script type="text/javascript">
(function() {
var disabledDays = ["2022-12-23","2022-12-24","2022-12-25","2022-12-30","2022-12-31","2023-1-1"];
var minDate = new Date();
var maxDate = new Date();
maxDate.setDate((maxDate.getDate()) + 60);
minDaysToShip = 2; // Default minimum days
if (minDate.getDay() == 5) {
// Friday. Set min day to Tuesday. 4 days from now.
minDaysToShip = 4;
} else if (minDate.getDay() == 6) {
// Saturday. Set min day to Tuesday. 3 days from now.
minDaysToShip = 3;
}
minDate.setDate(minDate.getDate() + minDaysToShip);
var picker = new Pikaday(
{
field: document.getElementById('ship_date'),
format: 'MM/DD/YYYY',
disableWeekends: 'true',
toString(date, format) {
// you should do formatting based on the passed format,
// but we will just return 'D/M/YYYY' for simplicity
const day = ("0" + date.getDate()).slice(-2);
// Get two digit month ("0" + (this.getMonth() + 1)).slice(-2)
const month = ("0" + (date.getMonth() + 1)).slice(-2);
const year = date.getFullYear();
return `${month}/${day}/${year}`;
},
parse(dateString, format) {
// dateString is the result of `toString` method
const parts = dateString.split('/');
const day = parseInt(parts[0], 10);
const month = parseInt(parts[1], 10) - 1;
const year = parseInt(parts[2], 10);
return new Date(year, month, day);
},
firstDay: 0,
minDate: minDate,
maxDate: maxDate,
disableDayFn: function(inputDate) {
// Disable national holidays
var formattedDate = inputDate.getFullYear() + '-' + (inputDate.getMonth() + 1) + '-' + inputDate.getDate();
return ((disabledDays.indexOf(formattedDate) == -1) ? false : true);
}
});
})();
</script>
This was fixed by replacing (function() with window.addEventListener("load", function()

Looping to grab HTML calendar date data attributes

I am manipulating a WordPress calendar plugin. I'm trying to add some CSS to the dates on the calendar for every day up to the current date. The plugin that I'm using, has the calendar in a table. The code for an individual day looks like this:
<td class="day-with-date" data-date="2017-5-10">
<div class="day-number">10</div>
</td>
I'm trying to use jQuery to loop through the dates from the data attribute.
This is my script.
$('.day-with-date .day-number').each(function(element){
var dataNumber = "[data-date=" + $(this).text() + "]";
var dataDateDay = "[data-date="+day+"]";
var textDay = $(this).text();
if(textDay <= day){
$('td.day-with-date .day-number').addClass('online-display');
}else if(textDay > day){
$('td.day-with-date .day-number').removeClass('online-display');
}else{
console.log("error douche");
}
});
What it's doing, is adding the CSS because textDay is <= than day. But it's removing the class after it's applied. I'm trying to get the CSS to add for all days up to today's date, then remove the CSS for days after.
How can I loop through the calendar dates, then apply my CSS class to all days up to the current date?
Thanks in advance!
There needs to be a change in your .each function:
$('.day-with-date .day-number').each(function(index) {
var dataNumber = "[data-date=" + $(this).text() + "]";
var dataDateDay = "[data-date=" + day + "]";
var textDay = $(this).text();
if (textDay <= day) {
$(this).addClass('online-display');
} else if (textDay > day) {
$(this).removeClass('online-display');
} else {
console.log("error douche");
}
});
You can try it here: https://jsfiddle.net/k99o5b39/
Try this
... // day has been defined
$('.day-with-date .day-number').each(function(element){
var parsedDay = Number.parseInt(element.text());
if(parsedDay <= day){
element.addClass('online-display');
} else {
element.removeClass('online-display');
}
});

minDate function dont work correctly in date picker with time picker

I using date & time picker but don't work bellow function correctly.
I guess the time picker minDate function jQuery UI have conflict with time picker
I'm change the location script and delete minDate functions in time picker but doesn't work correctly
jQuery('.datepicker1').datetimepicker({
onSelect: function(dateText, inst) {
jQuery('.datepicker2').datetimepicker({
minDate: new JalaliDate(inst['selectedYear'], inst['selectedMonth'], inst['selectedDay']),
});
},
});
can u help me please?
I use this
jQuery("#datepicker").datepicker({minDate:"+0d",onSelect:function(tarih){
jQuery("#datepicker2").datepicker("destroy");
var myDate = new Date(tarih)
myDate.setDate(myDate.getDate() + 1)
tarih = myDate.getFullYear().toString() + "/"
tarih += (myDate.getMonth() + 1).toString() + "/"
tarih += myDate.getDate().toString()
jQuery("#datepicker2").datepicker({minDate:tarih}).delay(100).val(tarih);
}});

Javascript Default Values reset on page reload

I am new to the javascript/aspx world and most of my programming was done through trial and error and lots of internet searching, but i've hit upon a problem i cannot find a solution for.
I have a popup page that has 2 input boxes, and i have managed to add default values to both of these input boxes, for dates, like so:
$(window).load(function () {
var now = new Date();
var month = (now.getMonth() + 1);
var day = now.getDate();
if (month < 10)
month = "0" + month;
if (day < 10)
day = "0" + day;
$('#FNewDate').val('01/' + month + '/' + now.getFullYear());
$('#TNewDate').val(day + '/' + month + '/' + now.getFullYear());
}
now, if the user has entered a new date and hits the submit button, the page posts and reloads with the calculated results displayed to the user AND THE DEFAULT VALUES again, but not with the new dates the user has entered, and i need it to stay with the entered information.
I have tried playing around with static members but i have not been able to get it to work.
Here is the button action:
<asp:Button ID = "Calculate" runat = "server"
style="width:40% ; font:15px arial" Text = "Calculate" onclick="Calculate_Click" />
any help on the above would be appreciated, and pls include code in your replies...
Thnks
You should change your default value setters to add
if ($('#FNewDate').val().length() != 0)
To only set the value in case the value coming from server is empty.
Then in your input
<input type="text" id="FNewDate" value="<%=someObject.getSomeDate()%>"/>

How to get the date from jQuery UI datepicker

I want to get the date from datepicker whenever user choose the date in jQuery UI datepicker and click the button on the form.
well I need to get the day, month and year of the date they choose. How can I get the date form jQuery UI?
Use
var jsDate = $('#your_datepicker_id').datepicker('getDate');
if (jsDate !== null) { // if any date selected in datepicker
jsDate instanceof Date; // -> true
jsDate.getDate();
jsDate.getMonth();
jsDate.getFullYear();
}
You can retrieve the date by using the getDate function:
$("#datepicker").datepicker( 'getDate' );
The value is returned as a JavaScript Date object.
If you want to use this value when the user selects a date, you can use the onSelect event:
$("#datepicker").datepicker({
onSelect: function(dateText, inst) {
var dateAsString = dateText; //the first parameter of this function
var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
}
});
The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.
See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.
Try this, works like charm, gives the date you have selected.
onsubmit form try to get this value:-
var date = $("#scheduleDate").datepicker({ dateFormat: 'dd,MM,yyyy' }).val();
Reference here
the link to getdate: https://api.jqueryui.com/datepicker/#method-getDate
$("#datepicker").datepicker( 'getDate' );
Sometimes a lot of troubles with it. In attribute value of datapicker data is 28-06-2014, but datepicker is show or today or nothing. I decided it in a such way:
<input type="text" class="form-control datepicker" data-value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" value="<?= date('d-m-Y', (!$event->date ? time() : $event->date)) ?>" />
I added to the input of datapicker attribute data-value, because if call jQuery(this).val() OR jQuery(this).attr('value') - nothing works. I decided init in cycle each datapicker and take its value from attribute data-value:
$("form .datepicker").each(function() {
var time = jQuery(this).data('value');
time = time.split('-');
$(this).datepicker('setDate', new Date(time[2], time[1], time[0], 0, 0, 0));
});
and it is works fine =)
NamingException's answer worked for me. Except I used
var date = $("#date").dtpicker({ dateFormat: 'dd,MM,yyyy' }).val()
datepicker didn't work but dtpicker did.
I just made some web scraping to discover the behaviour of JequeryUI datepicker, it was necessary for me because I'm not familiar with JS object so:
var month = $(".ui-datepicker-current-day").attr("data-month");
var year = $(".ui-datepicker-current-day").attr("data-year");
var day = $(".ui-state-active").text();
it just pick the value in relation of the changing of class, so you can implement the onchange event:
$(document).on('change', '#datepicker', function() {
var month = $(".ui-datepicker-current-day").attr("data-month");
var year = $(".ui-datepicker-current-day").attr("data-year");
var day= $(".ui-state-active").text();
$("#chosenday").text( day + " " + month + " " + year ) ;
});
or check if the current day is selected:
if( $("a").hasClass("ui-state-active") ){
var month = $(".ui-datepicker-current-day").attr("data-month");
var year = $(".ui-datepicker-current-day").attr("data-year");
var day= $(".ui-state-active").text();
$("#chosenday").text( day + " " + month + " " + year );
}

Categories

Resources