I recently was trying to set the default date of a DatePicker that I added to a input field.
form.find('#expires').datepicker( {defaultDate: 7} );
However, the DatePicker would keep displaying the default date value of "1/1/2020". This was driving me nuts as I was looking through the documentation and searching online (i.e. SO) for solutions to my problem to no avail.
http://api.jqueryui.com/datepicker/#option-defaultDate
http://stackoverflow.com/questions/14580749/jquery-datepicker-set-default-date
Root Cause:
After intense thinking and investigation, I finally found my root cause. I already set the predefined value in the field itself which was overriding my jquery default property.<input type="text" name="expires" class="expires" id="expires" placeholder="Expires" value="1/1/2020" />
Solution #1:
Remove the attribute value in the input field or replace the value with expected default value before passing field to DatePicker.I chose to replace the value upon displaying of the input field because without the value attribute the input field displays null by default and the DatePicker would open with a default date. I wanted a default date in the input field AND in the DatePicker.
<input type="text" name="expires" class="expires" id="expires" placeholder="Expires" value="1/1/2020" />
form.find('#expires').val( _getDefaultExpirationDate() );
form.find('#expires').datepicker();
/**
* Get Default Expiration Date
* @return (string) current date + 1 month in format: MM/DD/YYYY
*/
function _getDefaultExpirationDate()
{
var today = new Date();
return tens(today.getUTCMonth()+ 1) +'/'+ tens(today.getUTCDate()) +'/'+ today.getUTCFullYear();
}
/**
* Tens
* - converts an integer that's a single digit into double digits
* - useful for dates and times
* @param (int) integer
* @return (string) single digit with leading '0' or double digit
*/
function _tens (integer)
{
while (integer > 99 )
{
integer = integer - 100;
}
return (integer < 10) ? "0"+integer : integer;
}
Easier Solution:
Change the input type from 'text' to 'date' and set default value.http://www.w3schools.com/jsref/prop_date_value.asp
<input type="date" name="expires" class="expires" id="expires" placeholder="Expires" value="1/31/2016" />
Happy Coding!,G2
No comments:
Post a Comment