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

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

Related

How to set min and max date in the JQueryUI DatePicker in ASP.Net MVC 5 Application

Ok, so after following this Date Picker Tutorial I am able to create a datepicker. But I want to set some limit to the date picker. For example I only want the date picker to allow from 5th Jan 2017 to 5th Aug 2017". How can I achieve this. Note that I don't want to change the dateFormat property of the datepicker. Also, dateformat property is working properly.
Below is what I have till now:
<script type="text/javascript">
$(function () {
$(".date-picker").datepicker({
dateFormat: 'dd-M-yy',
minDate: '05-Jan-17',
maxDate: '05-Aug-17'
});
});
</script>
I selected minDate as '05-Jan-17' because I thought it should be put in the same format as I have set the dateFormat as dd-M-yy.
Documentation of JQuery UI:
After going through the Documentation of JQUERY DatePicker I thought I need to do something like below.
<script type="text/javascript">
$(function () {
$(".date-picker").datepicker({
dateFormat: 'dd-M-yy',
});
$(".date-picker").datepicker("option", "minDate", "05-JAN-17");
});
</script>
But this also does not work. Please help me.
Model Class
public class Genre
{
public int Id { get; set; }
[DisplayFormat(DataFormatString = "{0:dd-MMM-yyyy}", ApplyFormatInEditMode = true)]
public DateTime SongDate { get; set; }
}
EDIT 1:
This also does not work.
$(".date-picker").datepicker("option", "minDate", new Date("05-Jan-2017"));
EDIT 2
Below change worked
$(".date-picker").datepicker("option", "minDate", new Date("01-05-2017"));
$(".date-picker").datepicker("option", "maxDate", new Date("08-05-2017"));
minDate , maxDate should be Date object instead of string, so create a
new Date(....) in minDate and maxDate accordingly as per your requirement.
for reference, read this question

jQuery UI datepicker with multiple altField and altFormat

I am trying to define a date input field with two alt date display fields where they all have distinct date formats. In the example below, if my date input is 013017 then I want my alt date display fields to show
Display 1: 2017-01-30
Display 2: 01-30-17
But instead I'm getting
Display 1: 2017-01-30, 01-30-17
Display 2: 2017-01-30, 01-30-17
Here is my markup:
<p>Date Input: <input type="text" id="datepicker1"> </p>
<p>Display 1: <input type="text" id="alternate1" size="30"> </p>
<p>Display 2: <input type="text" id="alternate2" size="30"> </p>
Here is my js:
$( function() {
$( "#datepicker1" ).datepicker({
dateFormat: "mmddy",
altField: "#alternate1, #alternate2",
altFormat: "yy-mm-dd, mm-dd-y"
});
});
here is a jsfiddle: https://jsfiddle.net/5rqtj056/
The altFormat property accepts one format date, to be used for representing elements retrieved by the altField selector.
This a snippet from jQuery UI official documentation
altFormat
Type: String
Default: ""
The dateFormat to be used for the altField option. This allows one date format to be shown to the user for selection purposes, while a different format is actually sent behind the scenes. For a full list of the possible formats see the formatDate function
In order to do that, you need to bind an event on the #alternate1 for example and filling that one, you will convert the date and then fill the #alternate2
Here your new JS code:
$( function() {
$( "#datepicker1" ).datepicker({
dateFormat: "mmddy",
altField: "#alternate1",
altFormat: "yy-mm-dd",
onSelect: function(dateText) {
$('#alternate1').trigger("change");
}
});
$("#alternate1").change(elaborateDate);
$("#datepicker1").keyup(elaborateDate);
function elaborateDate() {
var alt1Date = $('#alternate1').val();
var newDate = $.datepicker.formatDate( "mm-dd-y", new Date(alt1Date) );
$('#alternate2').val(alt1Date);
}
});
https://jsfiddle.net/5rqtj056/8/

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

JQuery Datepicker - Send selected date to a new page, using it as a php variable

EDIT
I got it working puting the date behind the url to the target site. On the other side I'm using $_GET['val'] to get the value. But this way too hacky and I'd love to see an more secure solution. But for now it works.
What I'm trying to achieve
Page 1:
Showing a datepicker. The user clicks on a date and gets directed to "Page 2".
Page 2:
Showing the previously selected date.
Whats the problem?
How do I send the selected date to a new page (so I can store the date in a php variable). Also I want to direct the user to the new page automatically after selecting a date.
This is what I got so far:
index.php (containing the datepicker)
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
var date = $('#datepicker').val();
alert(date);
$.post('getdate.php', {'val': dateText});
}
});
});
getdate.php
<?php
$value = $_POST['val'];
echo "I got your value! $val";
?>
The alert shows the selected date, so the variable is containing the date. But I can't get it so send it to my next page.
Thanks for helping!
you are posting dateText...try posting date like:
$.post('getdate.php', {'val': date});
You have a lot of options to make it work. Here are three of them:
1) Send the selected date to page 2 as a query parameter:
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
var date = $('#datepicker').val();
window.location.href = 'page2.php?date=' + date;
}
});
});
2) Put your datepicker insider a form and submit it after date selection.
3) Store the date in session inside your getdate.php file:
if (!empty($_POST['val'])) {
session_start();
$_SESSION['current_date'] = $_POST['val'];
}
... and check inside your second page:
//page2.php
session_start();
if (!isset($_SESSION['current_date'])) {
header('Location:index.php'); //redirect to first page if date not set
}
$selectedDate = $_SESSION['current_date'];
....
Choose the one that fits better your problem.
Your script is sending the date to the script getdate.php. But you do not see it i the browser because your ajax post does not send the user to the page. For this you would need to direct the script to that page, and one approach would be using a form:
index.php should also have a form:
<form id="hiddenfrm" action="getdate.php" method="post">
<input type="hidden" name="val" id="val" />
</forms>
<script>
$( function() {
$( "#datepicker" ).datepicker({
onSelect: function(dateText, inst) {
var date = $('#datepicker').val();
$('#val').val(date);
$('hiddenfrm').submit();
}
});
});
</script>
It may also be as simple as the val parameter is in quotes and I don't think it should be.
$.post('getdate.php', {val: date});

set or show date in textbox with jquery-ui datepicker

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

Categories

Resources