JQuery datepicker init the selector/field
-
21-08-2019 - |
Question
is it possible to fill the input field with a date which uses the same format as i would select it with the datepicker? For example i have a value (e.g. new Date()) in my input field before i select a date with the datepicker and i want it to have the same format as i would select it.
thx
kukudas
Solution
Check out the demo site, new Date().asString() is used to select today and it is formated, as one would expect.
$('.date-pick').datePicker().val(new Date().asString()).trigger('change');
EDIT:
You have to make sure, you set the Date.format correctly. Here is a working example for the german date format:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>jQuery datePicker simple datePicker demo</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/date.js"></script>
<script type="text/javascript" src="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/jquery.datePicker.js"></script>
<link rel="stylesheet" type="text/css" media="screen" href="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/styles/datePicker.css">
<script type="text/javascript" charset="utf-8">
Date.format = 'dd.mm.yyyy';
$(function(){
$('.date-pick').datePicker()
.val(new Date().asString()).trigger('change');
});
</script>
</head>
<body>
<label for="date1">Date 1:</label>
<input name="date1" id="date1" class="date-pick" />
</body>
</html>
Note, the script http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/scripts/date.js extends the Date.prototype and sets "Date.format" to 'dd/mm/yyyy'. I'm overriding this with 'dd.mm.yyyy'.
OTHER TIPS
I'm not sure I really understand what the problem is?
$(document).ready(function() {
$('#date_field').datepicker({
dateFormat: 'yy-mm-dd',
constrainInput: false});
});
and just have a standard value in the input field you have:
<input name="date_field" id="date_field" value="2008-04-16" />
or you could just set the value in document.ready
$('#date_field').val("2008-04-16");
after you add the datepicker. I'm not sure if that's what you mean?
Ok, after your comment I have a feeling you want something similar to this:
var my_date = new Date(); //This is the Date object that you're getting from external source
$('#date_field').val(my_date.getFullYear()+"/"+my_date.getMonth()+"/"+my_date.getDate());
This should set the value in the field to be 2008/04/26 (or whatever)