How do I pre-populate a jQuery Datepicker textbox

2019-01-02 22:33发布

I have a very simple jQuery Datepicker calendar:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
});

and of course in the HTML...

<input type="text" size="10" value="" id="date_pretty"/>

Today's date is nicely highlighted for the user when they bring up the calendar, but how do I get jQuery to pre-populate the textbox itself with today's date on page load, without the user doing anything? 99% of the time, the today's date default will be what they want.

18条回答
倾城 Initia
2楼-- · 2019-01-02 23:06

Set to today:

$('#date_pretty').datepicker('setDate', '+0');

Set to yesterday:

$('#date_pretty').datepicker('setDate', '-1');

And so on with any number of days before or after today's date.

See jQuery UI › Methods › setDate.

查看更多
小情绪 Triste *
3楼-- · 2019-01-02 23:07

The solution is:

$(document).ready(function(){
    $("#date_pretty").datepicker({ 
    });
    var myDate = new Date();
    var month = myDate.getMonth() + 1;
    var prettyDate = month + '/' + myDate.getDate() + '/' + myDate.getFullYear();
    $("#date_pretty").val(prettyDate);
});

Thanks grayghost!

查看更多
倾城 Initia
4楼-- · 2019-01-02 23:07

In order to set the datepicker to a certain default time (the current date in my case) on loading, AND then have the option to choose another date the syntax is :

    $(function() { 
        // initialize the datapicker
        $("#date").datepicker();

        // set the time
        var currentDate = new Date();
        $("#date").datepicker("setDate",currentDate);

    //  set the options for the button  
        $("#date").datepicker("option",{
            dateFormat: 'dd/mm',
            showOn: "button",
          // whatever option Or event you want 
        });
  });
查看更多
我只想做你的唯一
5楼-- · 2019-01-02 23:09

Update: There are reports this no longer works in Chrome.

This is concise and does the job:

$(".date-pick").datepicker('setDate', new Date());
查看更多
6楼-- · 2019-01-02 23:10

Just thought I'd add my two cents. The picker is being used on an add/update form, so it needed to show the date coming from the database if editing an existing record, or show today's date if not. Below is working fine for me:

    $( "#datepicker" ).datepicker();
    <?php if (!empty($oneEVENT['start_ts'])): ?>
       $( "#datepicker" ).datepicker( "setDate", "<?php echo $startDATE; ?>" );
    <? else: ?>
       $("#datepicker").datepicker('setDate', new Date());   
    <?php endif; ?>
  });
查看更多
7楼-- · 2019-01-02 23:13

To pre-populate date, first you have to initialise datepicker, then pass setDate parameter value.

$("#date_pretty").datepicker().datepicker("setDate", new Date());
查看更多
登录 后发表回答