Datepicker:将输入值设置为当前日期 [英] Datepicker: Setting input value to current date

查看:771
本文介绍了Datepicker:将输入值设置为当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Bootstrap中使用这个插件,日期选择 http://eternicode.github.io/ bootstrap-datepicker /

I am using this plugin for Bootstrap, for date picking http://eternicode.github.io/bootstrap-datepicker/

我在这里工作 FIDDLE
但我不知道这是否是正确的方法?或者如果有办法通过插件来做到这一点。我已经尝试了,但我没有得到正确的。

I have it working here FIDDLE But I dont know if this is the right way to do it? Or if there's a way to do it through the plugin. I've tried to but I haven't got it right.

HTML:

Date: <input type="text" name="" class="datepicker" />

Jquery:

var d = new Date();

var month = d.getMonth()+1;
var day = d.getDate();

var output =((''+month).length<2 ? '0' : '') + month +  '/' + ((''+day).length<2 ? '0' : '') + day + '/' + d.getFullYear();

$('.datepicker').datepicker();

$('.datepicker').val(output);

所以我使用Jquery获取当前日期,然后我只是启动datepicker,然后设置输入值为当前日期。

So I'm using Jquery to get the current date then I just fire the datepicker and then set the input value to the current date.

任何其他想法或建议将不胜感激!

Any other ideas or suggestions will be appreciated!

推荐答案

你的方法很好。

然而,你可以减少一些字符 - 如果你愿意的话 - / p>

You could, however, reduce it a couple of characters - if you'd like - to something like this:

var d = new Date(),
    output = [
        ('0' + (d.getMonth() + 1)).substr(-2), 
        ('0' + d.getDate()).substr(-2), 
        d.getFullYear()
    ].join('/');

$('.datepicker').datepicker().val(output);

另外 - 如果您正在做更多的工作日期 - 这可能是一个好主意查看一些日期库,如 date.js sugar.js ,那么你可以这样做:

Also - if you're doing more work with dates - it might be a good idea to have a look at some date libraries, like date.js or sugar.js, then you could do something like this:

$('.datepicker').val(new Date().toString('MM/dd/yyyy'));        // date.js
$('.datepicker').val(Date.create().format('{MM}/{dd}/{yyyy}')); // sugar.js

这篇关于Datepicker:将输入值设置为当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆