加载时自动将选定日期设置为 altField
我想在加载页面时设置 datepicker 字段和 altField
的值,我想知道 datepicker 中是否有一个选项可以自动执行此操作(即无需调用 设置日期
)。
我知道,如果我这样做:
$("#date-div").datepicker({altField:"#date-input",altFormat:"yy-mm-dd", defaultDate:+7});
将 date-div
作为 div
时,默认日期会自动添加到 date-input
页面加载时的字段。 但是,如果我使用文本字段而不是 div
,它不会自动设置值(我必须在单独的行中调用 setDate
)。
我只是对此感到好奇,我已经通过调用 setDate 实现了它,但我想知道是否有东西可以自动执行,如果不是为什么? (因为它在使用 div 显示日历时确实有效)。
I want to set the values of the datepicker field and the altField
when the page is loaded, and I was wondering if there's an option in the datepicker to do that automatically (i.e. without having to call setDate
).
I know that if I do something like this:
$("#date-div").datepicker({altField:"#date-input",altFormat:"yy-mm-dd", defaultDate:+7});
With date-div
being a div
, the default date is automatically added to the date-input
field when the page is loaded.
But if I use a text field instead of a div
it doesn't set the values automatically (I have to call setDate
in a separate line).
I'm just curious about this, I have already implemented it calling setDate, but I would like to know if there's something to do it automatically and if not why? (since it does work when using a div to display the calendar).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
设置
defaultDate
的最佳选择是使用 Moment.js,因为解析日期的浏览器实现不可靠。例如,如果您的altField
是日期选择器字段之前的字段并且采用 ISO 8601 格式,您可以执行以下操作:这只会在打开日历时设置默认选定的日期。如果您还想填充日期选择器字段,可以在使用上面的代码初始化日期选择器后执行此操作:
Your best bet to set the
defaultDate
is to parse the value of thealtField
with a library like Moment.js, because browser implementations for parsing dates are unreliable. For example, if youraltField
is the field before your datepicker field and it's in ISO 8601 format, you can do this:That will only set the default selected date when opening the calendar. If you also want to populate the datepicker field, you can do this after having initialised the datepicker with the code above:
不是 100% 优雅,因为它需要重复,但它对我有用:
Not 100% elegant as it needs repetition but it works for me: