html5 datepicker jquery min max and format - javascript

I wrote a simple function to set min/max dates for datepicker and format selected date.
But when I set the range the format returns to default mm/dd/yy
Please note that the page in HTML5.
and here the code
$(function () {
var pickerFormat = {
dateFormat: "dd/mm/yy"
};
var range = {
minDate: "-2y",
maxDate: new Date()
};
$("#datepicker1").datepicker(range, pickerFormat);
});

Use the same object for both date format and picker range.
for example
$(function () {
var pickerFormatrange = {
dateFormat:"dd/mm/yy",
minDate: "-2y",
maxDate: new Date()
};
$("#datepicker1").datepicker(pickerFormatrange);
});

Related

Using datepicker in jquery to keep start date less than end date and allowing no weekends selection

I am new to jQuery and JSP. I am trying to make a booking system which has two dates - start date and end date. I require the following functionalities to be included in the system.
Start date should be less than end date and end date should be more than start date.
Booking should be allowed only on weekdays.
Format of date should be dd-mm-yy.
I was able to achieve all these functionalities individually but when I merge them either of them does not work.
Here is the jQuery code for start date should be less than end date and end date should be more than start date.
<script>
$(document).ready(function () {
$("#datepick").datepicker({
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate());
$("#datepick1").datepicker("option", "minDate", dt);
}
});
$("#datepick1").datepicker({
onSelect: function (selected) {
var dt = new Date(selected);
dt.setDate(dt.getDate());
$("#datepick").datepicker("option", "maxDate", dt);
}
});
});
</script>
And this is the jQuery code for disabling weekends and changing the date format.
<script>
$(document).ready(function () {
$("#datepick").datepicker({
dateFormat: "dd-mm-yy",
beforeShowDay: $.datepicker.noWeekends
});
$("#datepick1").datepicker({
dateFormat: "dd-mm-yy",
beforeShowDay: $.datepicker.noWeekends
});
});
</script>
I tried combining these two but either one of the functionality does not work.
Thank you in advance!!!
You can easily achieve that with just a bit of CSS:
th.ui-datepicker-week-end,
td.ui-datepicker-week-end {
pointer-events: none;
opacity: 0.5;
}
This will target datepicker CSS class weekends and set it to not clickable and opacity same as you would using datepicker JS.
And to get around date format not working use this:
var res = selected.split("-");
var newdate = [];
newdate.push(res[2],res[1],res[0] );
datepicker excepts 2015-03-25 and outputs this kind of format in selected:
2015-03-25T12:00:00-06:30
so when you set your date format it does not produce it right in . So you split your format, and rearrange it in your case from: 22-07-2020 to 2020-07-22 then datepicker new date function starts working again.
So now you can use your date range function as before just with added dateFormat: "dd-mm-yy", and code above. Example:
$(document).ready(function() {
$("#datepick").datepicker({
dateFormat: "dd-mm-yy",
onSelect: function(selected) {
var res = selected.split("-");
var newdate = [];
newdate.push(res[2],res[1],res[0] );
var dt = new Date(newdate);
dt.setDate(dt.getDate());
$("#datepick1").datepicker("option", "minDate", dt);
}
});
$("#datepick1").datepicker({
dateFormat: "dd-mm-yy",
onSelect: function(selected) {
var res = selected.split("-");
var newdate = [];
newdate.push(res[2],res[1],res[0] );
var dt = new Date(newdate);
dt.setDate(dt.getDate());
$("#datepick").datepicker("option", "maxDate", dt);
}
});
});
th.ui-datepicker-week-end,
td.ui-datepicker-week-end {
pointer-events: none;
opacity: 0.5;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<input type="text" id="datepick" name="date"><input type="text" id="datepick1" name="date">

why jquery-ui-datepicker accepts invalid values from keyboard

I am using jquery UI date-picker to get the date with min and max date range value, it's working on selecting the date using the date-picker widget, but it gets invalid values using the keyboard. I want to get the date by keyboard as well as mouse. Please help me to get valid date value or to show an error message of the invalid date value.
datepicker
You can use code as below :
<script type="text/javascript">
$(".datePicker").datepicker({
dateFormat: 'd/mm/yy',
changeMonth: true,
changeYear: true,
firstDay: 1,
minDate: Date.parse("1900-01-01"),
maxDate: Date.parse("2100-01-01"),
yearRange: "c-90:c+150"
});
$(function () {
$.validator.addMethod(
"date",
function (value, element) {
// Here you can set date range
var minDate = Date.parse("1900-01-01");
var maxDate = Date.parse("2100-01-01");
var valueEntered = Date.parse(value);
if (valueEntered < minDate || valueEntered > maxDate) {
return false;
}
return !/Invalid|NaN/.test(new Date(minDate));
},
"Please enter a valid date!"
);
});
</script>

datepicker in javascript date format DD/MM/YYYY

Am using a datepicker in my application.
code is :
this.$el.find('#ondate').datepicker({
minDate: 0,
maxDate: "+2M",
onSelect: function(x) {
self.startDepartureValidation();
return self.onDate(x);
},
// numberOfMonths: numberOfMonths,
beforeShow: function() {
return $('#ondate').datepicker("option", "maxDate", $("#returndate").datepicker('getDate'));
}
});
when i seklect the date am getting the format as MM/DD/YYYY but i need as DD/MM/YYYY in the textbox.
if i use the dateformat: in datepicker i will get that format but , with MM/DD/YYYY am having so many calculations in my application.
Note: i need just in datepicker textbox after seklecting date it should show in that textbox as DD/MM/YYYY. without changing in our code in other places
Add the dateFormat attribute to your code:
this.$el.find('#ondate').datepicker({
minDate: 0,
maxDate: "+2M",
dateFomat: 'dd/mm/yy', //Note that 'yy' is for four digits.
onSelect: function(x) {
self.startDepartureValidation();
return self.onDate(x);
},
// numberOfMonths: numberOfMonths,
beforeShow: function() {
return $('#ondate').datepicker("option", "maxDate", $("#returndate").datepicker('getDate'));
}
});
More details at the official documentation here.
The below snippet of code can help in converting date format:-
var ddMMyy = $("#ondate").val().split("/");
var mmDDyy = ddMMyy[1]+"/"+ddMMyy[0]+"/"ddMMyy[2];
alert(mmDDyy);
Working JSFiddle here.

How to get the selected date from jquery datepicker

I am using jquery datepicker to show a calendar.Now as per my requirement i want to get the date selected by the user in my jquery variable which i will use in my application but i am not able to get the date ..
Here is the code for datepciker
<div id="datepicker"></div>
and here i am trying to get the selected code..
$(document).ready(function () {
$("#datepicker").datepicker({
onSelect: function (dateText, inst) {
var date = $(this).val();
alert(date);
}
});
});
But, I am not able to get the date ..Please help me ..Thanks..
This should do the trick
$(function() {
$("#datepicker").datepicker();
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
It's basic but here is a jsfiddle with it alerting the selected date when selected
update to change the date format
$(function() {
$( "#datepicker" ).datepicker({ dateFormat: "yy-mm-dd" });
$("#datepicker").on("change",function(){
var selected = $(this).val();
alert(selected);
});
});
jsfiddle
3rd update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).val();
alert(selected);
}
});
});
I have used a little more of the native markup for datepicker ui here try this and see if you get the alert as you are after.
4th Update
$(function() {
$("#datepicker").datepicker({
dateFormat: "yy-mm-dd",
onSelect: function(){
var selected = $(this).datepicker("getDate");
alert(selected);
}
});
});
The 4th method uses $(this).datepicker("getDate") instead of $(this).val() as $(this).datepicker("getDate") returns a date object and $(this).val() returns the date as a string.
Depending on your needs select which one is appropriate.
(Added 4th method and explanation of the difference after #TimothyC.Quinn commented that the getDate being the correct method)
Though, question is answered, for people who just want a date object or set a date with specific format. There is simple functions jQuery provides. Here's working jsfiddle
$( "#datepicker" ).datepicker({ dateFormat: "dd-mm-yy" });
$("#datepicker").datepicker('setDate', '10-03-2020');
// pass string of your format or Date() object
$("#datepicker").datepicker('getDate');
// returns Date() object
$("#another_datepicker").datepicker('setDate', $("#datepicker").datepicker('getDate'));
// pass string of your format or Date() object
Try
$("#datepicker").datepicker({
onSelect:function(selectedDate)
{
alert(selectedDate);
}
});
OR
$("#datepicker").datepicker({
onSelect:function (dateText, inst)
{
alert(inst);
}
});
try this
$('.selector').datepicker({
onSelect: function(dateText, inst) { ... }
})
you have two elements with the class .datepicker, the selector won't know which element to choose from. So, you'll have to specify the name of the input you're trying to get the date from
first = $(".datepicker[name=datepicker1]").datepicker('getDate');
second = $(".datepicker[name=datepicker2]").datepicker('getDate');
You can use the changeDate event outlined here instead of onSelect and then reference e.date or e.dates. See the JSON below.
HTML:
<div id='QA'></div>
<div id='datepicker'></div>
JS:
<script type="text/javascript">
$(function() {
$('#datepicker').datepicker({
clearBtn: true,
todayHighlight: false,
multidate: true
}) .on('changeDate', function(e){
$('#QA').html(JSON.stringify(e));
});
});
/*
{
"type":"changeDate",
"date":"2015-08-08T07:00:00.000Z",
"dates":[
"2015-08-08T07:00:00.000Z"
],
"timeStamp":1438803681861,
"jQuery21409071635671425611":true,
"isTrigger":3,
"namespace":"",
"namespace_re":null,
"target":{
},
"delegateTarget":{
},
"currentTarget":{
},
"handleObj":{
"type":"changeDate",
"origType":"changeDate",
"guid":52,
"namespace":""
}
}
*/
</script>
The ideal way is to get the date and convert it to a common format and utilize the same. (may passing to server or so.)
$("#datepicker").datepicker('getDate').toISOString()
so it will get the date in ISO stander.
All code is for Bootstrap Datepicker
var calendar = $('#calendar').datepicker("getDate"); // Ex: Tue Jun 29 2021 00:00:00 GMT+0600 (Bangladesh Standard Time)
or
var calendar = $('#calendar').data('datepicker').getFormattedDate('yyyy-mm-dd'); // Ex: 2021-06-30
if(calendar){
alert(calendar);
} else {
alert('null');
}
If you need it in specific format like '2021/09/28':
$.datepicker.formatDate('yy/mm/dd',
$('.date-picker-2').datepicker("getDate")
);
Here is how to get Date object from datepicker in the onSelect event:
$("#datepickerid").datepicker({
onSelect: function (dateText, inst) {
var date_obj = $(this).datepicker('getDate');
}
});
I find it strange that the onSelect caller would not return the date object by default.

DatePicker Start Date and Finish Date Validation without plugin

Using Asp.Net MVC 4 with JqueryUI.
I have 2 textboxes which provide me datepickers. I need validation for; start date can be equal to finish date and finish date can not be less from start date.
Datepicker script code;
<script>
$(function () {
$(".date").datepicker({
changeMonth: true,
changeYear: true
});
});
</script>
My textboxes:
<td>#Html.TextBoxFor(model => model.StartDate, "{0:dd.MM.yyyy}", new { #class = "date", #id="dt1" }) </td>
<td>#Html.TextBoxFor(model => model.FinishDate, "{0:dd.MM.yyyy}", new { #class = "date", #id="dt2" }) </td>
I found this code from this subject. But i can't get validation. I cant figure out what's the problem. All helps will be appreciated.
$(document).ready(function () {
$("#dt1").datepicker({
dateFormat: "dd-M-yy",
minDate: 0,
onSelect: function (date) {
var dt2 = $('#dt2');
var startDate = $(this).datepicker('getDate');
var minDate = $(this).datepicker('getDate');
dt2.datepicker('setDate', minDate);
startDate.setDate(startDate.getDate() + 30);
//sets dt2 maxDate to the last day of 30 days window
dt2.datepicker('option', 'maxDate', startDate);
dt2.datepicker('option', 'minDate', minDate);
$(this).datepicker('option', 'minDate', minDate);
}
});
$('#dt2').datepicker({
dateFormat: "dd-M-yy"
});
});
JQuery - end date less than start date
I think this may helps you, when you changes one of the datepickers will show an error if both are different. and also se the isValid variable to false too stop it from being able to submit
<script>
var isValid=true;
$(function () {
$(".date").datepicker({
changeMonth: true,
changeYear: true,
onSelect: function() {
var date1 = $("#dt1").datepicker('getDate');
var date2 = $("#dt2").datepicker('getDate');
if (date1.getDate() === date2.getDate() &&
date1.getMonth() === date2.getMonth() &&
date1.getFullYear() === date2.getFullYear())
{
isValid=false;
//ALERT error
}
}
});
});
</script>

Categories