neubert
neubert

Reputation: 16792

unable to set default date with jquery ui's datepicker

My HTML:

<input type="text" name="day" id="date">

My Javascript:

$(function() {
    $('#date').datepicker({
        'dateFormat': 'yy-mm-dd',
        'defaultDate': '2015-12-18'
     });
});

The #date text box is being turned into a datepicker, so that's working. And the format is in the format I'm telling it to be in. But the default date option doesn't seem to be doing anything.

In this example I'd expect the textbox to appear with "2015-12-18" when the page is first loaded. If I click on the textbox the datepicker dialog will come up and I can enter in a different date but the date of "2015-12-18" should be displaying until I've done that. But it isn't and I don't understand why.

My JS Fiddle:

https://jsfiddle.net/18000rLe/4/

Upvotes: 3

Views: 7547

Answers (4)

DinoMyte
DinoMyte

Reputation: 8858

Try this.

Couple of things to keep in mind -->

1. defaultDate option would set the date in the datepicker calender, not in the input field. For that, you need to explicitly define the setDate.
2. If you use 'setDate' in the datepicker, you don't need to add defaultDate as the datepicker would automatically pick the date from the input field.

  $(function() {
        $("#date").datepicker({dateFormat: 'yy-mm-dd'});
        $("#date").datepicker('setDate', new Date('2014-12-18')); 
    }); 

Example : http://jsfiddle.net/DinoMyte/tXyLn/527/

Upvotes: 12

aabiro
aabiro

Reputation: 4238

I had to pass in date this way instead of Date object:

$('#date input').datepicker({
  'defaultDate': {
    year: 1999,
    month: 11,
    day: 31
 });

Upvotes: -1

Vince Verhoeven
Vince Verhoeven

Reputation: 1773

You can apply it like this:

$(function() {
    $('#date').datepicker({
        'dateFormat': 'yy-mm-dd',
      //'defaultDate': +7
      //'defaultDate': new Date(1985, 00, 01),
      'defaultDate': '2015-12-18'
     }).datepicker("setDate",new Date());
});

Upvotes: 0

Alaa M. Jaddou
Alaa M. Jaddou

Reputation: 1189

you could use this it will give you the date :)

$(function() {
var today = new Date();
    var dd = today.getDate();
    var mm = today.getMonth()+1; //January is 0!
    var yyyy = today.getFullYear();
    if(dd < 10) {
        dd = '0' + dd;
    } 
    if (mm < 10) {
        mm = '0' + mm;
    } 
    today = yyyy + '-' + mm + '-' + dd;  
    $('#date').val(today);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="day" id="date">

Upvotes: 0

Related Questions