How to get the selected date from jquery datepicker - javascript

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.

Related

Set picked date to another datepicker with Materialize

I'm using Materialize to create an app with two datepickers:
$(document).ready(function(){
$('#outDate').datepicker({
format: 'dd-mm-yyyy'
});
});
$(document).ready(function(){
$('#returnDate').datepicker({
format: 'dd-mm-yyyy',
});
});
What i need to do is pass the selected date from datepicker 1 ('#outDate') and set into datepicker 2 ('#returnDate'). How can i do that. I've read the doc of Materialize, but i'm not getting any success.
Someone can help me, please?
Also i'm using Javascript and AngulrJs.
Thanx in advance.
you can do like this
$(document).ready(function(){
$('#outDate').datepicker({
format: 'dd-mm-yyyy',
onSelect: function(date) {
var date = $("#outDate").datepicker('getDate').getDate(); // get selected date of #outDate
$('#returnDate').datepicker('defaultDate ', new Date(date)); // set #outDate date to #returnDate
}
});
});
$(document).ready(function(){
$('#returnDate').datepicker({
format: 'dd-mm-yyyy',
});
});
Added working fiddle here

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.

Allow datepicker to show only specific month

I'm trying to crate a datepicker from jQuery.
Users will allow to choose only June to September in each year from 2016-2020.
(So I don't think minDate and maxDate will work here)
I tried using the "beforeShowDay" as mentioned in
Disable specific months JqueryUI datepicker
The code was successfully disable users from picking the date outside from June to September but they can still choose January-December from the month dropdownlist (of datepicker).
What I want to do is limit the datepicker month-drop-down-list to show only June to September.
$(document).ready(function() {
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays
});
var monthsToDisable = [0,1,2,3,4,9,10,11];
var endMonth=[8];
function disableSpecificWeekDays(date) {
var month = date.getMonth();
if ($.inArray(month, monthsToDisable) !== -1) {
return [false];
}
return [true];
}
$("#datepicker").datepicker("setDate",'06/01/2016');
});
I don't see any options that would allow you to adjust this. I have a hacky solution that will probably do the job for most use cases, but that's your call. What I have done here is remove the unwanted select items from the datepicker list each time it gets updated. I had to add a short delay as jQuery UI takes a second to generate its code.
var removeDisabledMonths = function() {
setTimeout(function() {
var monthsToDisable = [0,1,2,3,4,9,10,11];
$.each(monthsToDisable, function(k, month) {
var i = $('#ui-datepicker-div select.ui-datepicker-month').find('option[value="'+month+'"]').remove();
});
}, 100);
};
//datepicker
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays,
// Added this --
onChangeMonthYear: function(year, month, obj) {
removeDisabledMonths();
}
});
//initial hide
setTimeout(function() {
removeDisabledMonths();
}, 1000);
Note that I had to call the function with a 1 second delay after the datepicker was initialized in order to get the months to hide the first time. Hacky, but if you are only looking to adjust the UI for the user, it just may do the job.
Well, Christ's code will activate itself after you choose some month/date.
If you don't, the January,Feb..... still being shown.
Therefore I add "beforeShow:" and connect it to removeDisabledMonths();
Now it works better.
$("#datepicker").datepicker({
changeMonth: true,
changeYear: true,
yearRange:'2016:2020',
minDate:0,
beforeShowDay: disableSpecificWeekDays,
onChangeMonthYear: function(year,month,obj){
removeDisabledMonths();
}
});
var monthsToDisable = [0,1,2,3,4,9,10,11];
function disableSpecificWeekDays(date) {
var month = date.getMonth();
var day=date.getDate();
if ($.inArray(month, monthsToDisable) !== -1) {
return [false];
}
return [true];
}
$("#datepicker").datepicker("setDate",'06/01/2016');er code here
$( ".selector" ).datepicker( "option", "defaultDate", "2019-09-01" );
$( ".selector" ).datepicker( "option", "minDate","2019-09-01");
$( ".selector" ).datepicker( "option", "maxDate","2019-09-30");
This displays only the month of September in the calendar and stops the user from accessing other months.

Converting Date Format Of JQuery Datepicker

I have a JQuery Date Picker link to a HTML Form textbox. It enters the date in mm/dd/yyyy format. What I need is to convert this format to dd-mm-yyyy.
Can I do when the date just inserted or after inserted? If one or both can how can I do that?
I already tried the belo code. But it didn't work.
//Date Picker
$(function() {
$("#to_date").datepicker({ maxDate: new Date() },);
$("#from_date").datepicker({ maxDate: new Date() });
$("div.ui-datepicker").css( { "font-size": "10px" } );
$("#to_date").datepicker({ dateformat: "dd-mm-yyyy" }).val();
$("#from_date".datepicker({ dateformat: "dd-mm-yyyy" }).val();
});
The above also contains the statements to display the last day to select as today.
So what is with my code?
Thanks & regards,
Chiranthaka
Fiddle
$(function() {
$( "#datepicker" ).datepicker();
$( "#format" ).change(function() {
$( "#datepicker" ).datepicker( "option", "dateFormat", $( this ).val() );
});
});
See the fiddle.. i think this would help you
The way you are using format, it won't convert your date, instead it will just set a format to be used on that control.
So, you'l have to set format using / as you want it in mm/dd/yyyy
And, using javascript you have to convert it to dd-mm-yyyy
So,
$(function() {
$("#to_date").datepicker({ dateformat: "mm/dd/yyyy" });
});
Now while accessing it, you can convert it as following code:
var dt=$("#to_date").val();
var arr=dt.split("/");
var converted= arr[1]+"-"+arr[0]+"-"+arr[2];
console.log(converted);
dateformat is probably case sensitive and should be dateFormat http://api.jqueryui.com/datepicker/#option-dateFormat
$(function() {
$("#to_date, #from_date").datepicker({
maxDate: new Date(),
dateFormat: "dd-mm-yyyy"
});
$("div.ui-datepicker").css( { "font-size": "10px" } );
});
Please use the following code. Jquery options are case sensitive. So use dateFormat instead of dateformat. The format should be dd-mm-yy instead of dd-mm-yyyy
$(function() {
$("#from_date, #to_date").datepicker({ maxDate: new Date(), dateFormat: "dd-mm-yy" });
$("div.ui-datepicker").css( { "font-size": "10px" } );
});

html5 datepicker jquery min max and format

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);
});

Categories