set or show date in textbox with jquery-ui datepicker - javascript

I have problem to set or show date in datepicker textbox at firsttime
I have two textboxes, the one is for datepicker and the second is for alternate format.
<input type="text" id="birth_date_display" />
<input type="text" id="birth_date" />
and scripts like this
$( "#birth_date_display" ).datepicker({
dateFormat: "d M, yy",
altField: "#birth_date",
altFormat: "yy-mm-dd"
});
my question is, How if i have String like: var datebirth="2011-08-16"
then i want to set to the textbox.
i had try to make script like this:
document.getElementById("birth_date_display").value = datebirth; //it's NOT works
document.getElementById("birth_date").value = datebirth; //it's works
thanks :)

You want to use the setDate method on the DatePicker:
$( "#birth_date_display" ).datepicker("setDate", datebirth);
$( "#birth_date" ).datepicker("setDate", datebirth);
Edit: You could probably also do it this way, but I haven't tested it:
$( "#birth_date_display, #birth_date" ).datepicker("setDate", datebirth);

You just need to call the setDate DatePicker method. This will set the value of the DatePicker and update both text box elements with the appropriate value in the formats you specified for the dateFormat and altFormat.
var datebirth="2011-08-16";
$("#birth_date_display").datepicker("setDate",new Date(datebirth));

You may also try to format month names instead of integer
var Month = "Feb" //some month;
var Year = "2013" //some year;
var mydate = new Date('1 '+ Month + " " + Year);
$(".txtDate").datepicker('setDate', new Date(Year, mydate.getMonth(), 1));

Related

Jquery UI Datepicker Show Additional Disabled Dates

I am trying to show additional disabled dates for the datepicker. For instance, I have min date as 2-1-2018 and max date as 3-1-2018. Is there anyway way to show 1-1-2018 and 4-1-2018 as disabled? Here is what I have right now. I don't need to dynamically set the dates. I need to display additional disabled dates so the user can see a larger range of disabled dates.
beforeShow : function () {
if (attrs.selecteddate) {
/*
2018-10-29T00:00:00.000+0000 before
2018-10-29 after
Only need the 00-00-0000 part of the date to avoid time zone issues. QoT always returns 00T for timezone anyways.
*/
var formattedDate = attrs.selecteddate.split("T");
attrs["formattedDate"] = formattedDate[0].substring(5) + "-" + formattedDate[0].substring(0, 4);
/*z
Set the date that the calander will display.
Append universal date time zone so correct date will be set in Firefox. It replaces T00:00:00.000+0000 with T12:00:00Z
*/
jQuery(this).datepicker('setDate', new Date(formattedDate[0] + 'T12:00:00Z'));
}
jQuery(this).datepicker('option', {
minDate : ( attrs.edittype === 'single' ) ? incrementDate(attrs.mindate) : attrs.mindate,
maxDate : ( attrs.edittype === 'single' ) ? convertToDateObj(attrs.maxdate) : attrs.maxdate
});
},
This below js code will help you to change min and max date dynamically.
$(function(){
$("#fdate").datepicker({
formatDate:"dd-mm-yy",
onselect:function(){
//do stuff here
},
onclose:function(){
//do stuff here
}
});
var date1 = "15-11-2017";
var date2 = "17-11-2017"; //you can pass dynamically date
$("#fdate").datepicker("option", "minDate", date1);
$("#fdate").datepicker("option", "maxDate", date2);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<input id="fdate" type="text" name="date" />

If datepicker already has value run onselect anyway

Currently, I can select a date and it fills my input fields with the date for 7 days and the corresponding day of the week in another series on input fields (just 3 days in example below). This is working well, although I'm sure there is a more efficient way to write the same thing with arrays, I just have no idea.
However, if I get the start date from the database on page load rather than selecting it with datepicker, it obviously doesn't trigger the onselect event and the fields don't populate. How can I get it to populate the fields in both situations?
I was thinking a function that is run when either the datepicker input has a valid value or onselect, but having never really touched JS before this little project I'm in over my head.
$(function() {
$("#StartDate").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function(dateStr, inst) {
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
var Date1 = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date1.setDate(Date1.getDate('dd/mm/yy'));
$('#Date1').val(Date1.toLocaleDateString());
$('#Day1').val(weekday[Date1.getUTCDay()]);
var Date2 = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date2.setDate(Date2.getDate('dd/mm/yy') + 1);
$('#Date2').val(Date2.toLocaleDateString());
$('#Day2').val(weekday[Date2.getUTCDay()]);
var Date3 = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date3.setDate(Date3.getDate('dd/mm/yy') + 2);
$('#Date3').val(Date3.toLocaleDateString());
$('#Day3').val(weekday[Date3.getUTCDay()]);
}
});
});
What about a loop like this?
$(function() {
$("#StartDate").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: function(dateStr, inst) {
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
for(i=0;i<weekday.length;i++){
var Date = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date.setDate(Date.getDate('dd/mm/yy') + i); // "i" is the array index
$('#Date').val(Date.toLocaleDateString());
$('#Day').val(weekday[Date.getUTCDay()]);
}
});
});
EDIT --- I misunderstood the question.
So here is another try, since I'm still unsure to get it... But getting closer.
If #startDate is already populated onload, you wish to run the above script as if it was selected using the datepicker, right?
So assuming something like this, on PHP side, to fill the StartDate field:
<input type="text" id="startDate" value="<?php echo $date; ?>"></input>
I would get this function out of the datepicker init to be able to run it from elsewhere.
I've done a CodePen to test this.
// This is the function you had on select
var DayFill = function(dateStr, inst) {
var weekday=new Array(7);
weekday[0]="Monday";
weekday[1]="Tuesday";
weekday[2]="Wednesday";
weekday[3]="Thursday";
weekday[4]="Friday";
weekday[5]="Saturday";
weekday[6]="Sunday";
for(i=0;i<weekday.length;i++){
var Date = $.datepicker.parseDate('dd/mm/yy', dateStr);
Date.setDate(Date.getDate('dd/mm/yy') + i); // "i" is the array index
$('#Date'+i).val(Date.toLocaleDateString());
// Fix day number to fit the array index
var daynum = Date.getUTCDay()-1;
if(daynum==-1){
daynum=6;
}
$('#Day'+i).val(weekday[daynum]);
}
}
// This is your datepicker init
$("#StartDate").datepicker({
dateFormat: 'dd/mm/yy',
onSelect: DayFill // Call the FillDay function, now out of this init.
});
// Onload, run the DayFill function using the input value
$(document).ready(function(){
DayFill( $("#StartDate").val() );
});

Set default time in bootstrap-datetimepicker

I want to set default time in this datetimepicker as 00:01 for the current date. Anyone tried that before? Having a tough time with it. It Seems simple.
$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
I need to use setDate, but I'm not sure how. I checked their code, but did not find a parameter for that.
None of the above worked for me, however I had success setting the default at time of instantiation.
JQuery
<script type="text/javascript">
$(function () {
var dateNow = new Date();
$('#datetimepicker').datetimepicker({
defaultDate:dateNow
});
});
</script>
Set a default input value as per this GitHub issue.
HTML
<input type="text" id="datetimepicker-input"></input>
jQuery
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$("#datetimepicker-input").val(output + " 00:01:00");
jsFiddle
JavaScript date source
EDIT - setLocalDate/setDate
var d = new Date();
var month = d.getMonth();
var day = d.getDate();
var year = d.getFullYear();
$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
$("#startdatetime-from").data('DateTimePicker').setLocalDate(new Date(year, month, day, 00, 01));
jsFiddle
For use datetime from input value, just set option useCurrent to false, and set in value the date
$('#datetimepicker1').datetimepicker({
useCurrent: false,
format: 'DD.MM.YYYY H:mm'
});
i tried to set default time for a picker and it worked:
$('#date2').datetimepicker({
format: 'DD-MM-YYYY 12:00:00'
});
this will save in database as : 2015-03-01 12:00:00
used for smalldatetime type in sql server
It works for me:
<script type="text/javascript">
$(function () {
var dateNow = new Date();
$('#calendario').datetimepicker({
locale: 'es',
format: 'DD/MM/YYYY',
defaultDate:moment(dateNow).hours(0).minutes(0).seconds(0).milliseconds(0)
});
});
</script>
use this after initialisation
$('.form_datetime').datetimepicker('update', new Date());
Hello developers,
Please try this code
var default_date= new Date(); // or your date
$('#datetimepicker').datetimepicker({
format: 'DD/MM/YYYY HH:mm', // format you want to show on datetimepicker
useCurrent:false, // default this is set to true
defaultDate: default_date
});
if you want to set default date then please set useCurrent to false otherwise setDate or defaultDate like methods will not work.
This Works for me. I have to use specially date format like this 'YY-MM-dd hh:mm' or 'YYYY-MM-dd hh:mm'
$('#datetimepicker1').datetimepicker({
format: 'YYYY-MM-dd hh:mm',
defaultDate: new Date()
});
This is my solution for your problem :
$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm'
}).on('dp.change', function (e) {
var specifiedDate = new Date(e.date);
if (specifiedDate.getMinutes() == 0)
{
specifiedDate.setMinutes(1);
$(this).data('DateTimePicker').date(specifiedDate);
}
});
This also work for setting a default hour or both.
Note that this code sample works with the useCurrent: false parameter too.
When the user pick a date, we check if the minute is 0 (hard-coded default value). In this case, we set a 1. Then, the user cannot select 0.
I solved my problem like this
$('#startdatetime-from').datetimepicker({
language: 'en',
format: 'yyyy-MM-dd hh:mm',
defaultDate:new Date()
});
Momentjs.com has good documentation on how to manipulate the date/time in relation to the current moment. Since Momentjs is required for the Datetimepicker, might as well use it.
var startDefault = moment().startof('day').add(1, 'minutes');
$('#startdatetime-from').datetimepicker({
defaultDate: startDefault,
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
By using Moment.js, i able to set the default time
var defaultStartTime = moment(new Date());
var _startTimeStr = "02:00 PM"
if (moment(_startTimeStr, 'HH:mm a').isValid()) {
var hr = moment(_startTimeStr, 'HH:mm a').hour();
var min = moment(_startTimeStr, 'HH:mm a').minutes();
defaultStartTime = defaultStartTime.hours(hr).minutes(min);
}
$('#StartTime').datetimepicker({
pickDate: false,
defaultDate: defaultStartTime
});
This works for me after a long hours of search , This solution is for Bootstrap datetimepicker version 4. when you have to set the default date in input field.
HTML
"input type='text' class="form-control" id='datetimepicker5' placeholder="Select to date" value='<?php echo $myDate?>'// $myDate is having value '2016-02-23' "
Note- If You are coding in php then you can set the value of the input datefield using php, but datetimepicker sets it back to current date when you apply datetimepicker() function to it. So in order to prevent it, use the given JS code
JAVASCRIPT
<script>
$('#datetimepicker5').datetimepicker({
useCurrent: false //this is important as the functions sets the default date value to the current value
,format: 'YYYY-MM-DD'
});
</script>

Why does jQueryUI datepicker swap day and month on page reload?

I have an MVC3 application where one of the pages has a jQuery datepicker:
<script>
$(function () {
$("#expirationDate").datepicker();
$("#expirationDate").datepicker("option", "dateFormat", "dd/mm/yy");
});
</script>
using (Html.BeginForm())
{
#Html.TextBox("expirationDate")
<input type="submit" value="Submit" />
}
the controller action goes like this:
public ActionResult DoStuff(String expirationDate)
{
return View();
}
The datepicker looks just fine but behaves strangely.
I enter some date into it like for example 31/12/2012 for Dec 31 (note I specified the format to be dd/mm/yy) and press the button. Control goes into the controller and there I see that expirationDate variable holds 31/12/2012 value. Then the action returns and then I see the textbox being empty.
Then I try 10/12/2012 - it gets into the action but when the page is displayed again it turns into 12/10/2012 - clearly the month and the day are swapped. Perhaps in case of 31/12 it saw that swapping them would yield an invalid date and just discarded that.
Why do day and month get swapped despite the format being explicitly specified?
Here's how I fixed it. I changed
$("#expirationDate").datepicker();
$("#expirationDate").datepicker("option", "dateFormat", "dd/mm/yy");
to
$("#expirationDate").datepicker({ dateFormat: 'dd/mm/yy' });
and now it works just fine.
My guess is that the original code is just broken. I didn't craft the original code, I found it on the datepicker page.
the javascript format dd/mm/yy is 01/12/2012
in javascript yy has the same result as yyyy (this is because getYear() is deprecated in favor of getFullYear()
if you want only to get the last 2 digits of the year, you need to do the break yourself, either in javascript, like:
$(function() {
$( "#datepicker" ).datepicker({
changeMonth: true,
onClose: function( selectedDate ) {
var dt = new Date(selectedDate),
txt = (dt.getDate() + 100).toString().slice(1) + "/" +
(dt.getMonth() + 101).toString().slice(1) + "/" +
(dt.getFullYear()).toString().slice(2);
$( "#datepicker" ).val(txt);
}
});
$( "#datepicker" ).datepicker(
"option", "dateFormat", "dd/mm/yy"
);
});
but you specify you're using ASP.NET, I would prefer to do it over in .NET
string dt = Request["expirationDate],
expDate = DateTime.Parse(dt).ToString("dd/mm/yy");

Change date format on datepicker

Hi i using this code to show a expiration date based on the select.
<script>
$(function(){
$("#date_picker").datepicker();
$("#Plano_Id").change(function() {
var offset = +$(this).find("option:selected").attr("title"), /* get days to add on date*/
theDate = new Date();
theDate.setDate(theDate.getDate() + offset);
$("#date_picker").datepicker("setDate", theDate);
});
});
</script>
But this returns the date in this format mm/dd/yyyy. I'm trying to show dd/mm/yyyy
For setting the format for a specific date control
$('#datepicker').datepicker({ dateFormat: 'dd/mm/yyyy' });
For setting it throughout your site/page, use
$.datepicker.setDefaults({ dateFormat: 'dd/mm/yyyy' });
//Note:Call this before initializing any date pickers
Use the dateFormat option: http://jqueryui.com/demos/datepicker/#date-formats

Categories

Resources