加载时自动将选定日期设置为 altField

发布于 2024-12-25 12:08:10 字数 517 浏览 2 评论 0原文

我想在加载页面时设置 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

你在看孤独的风景 2025-01-01 12:08:10

设置 defaultDate 的最佳选择是使用 Moment.js,因为解析日期的浏览器实现不可靠。例如,如果您的 altField 是日期选择器字段之前的字段并且采用 ISO 8601 格式,您可以执行以下操作:

$(this).datepicker({
    altField: $(this).prev(),
    altFormat: $.datepicker.ISO_8601,
    defaultDate: moment($(this).prev().val()).toDate()
});

这只会在打开日历时设置默认选定的日期。如果您还想填充日期选择器字段,可以在使用上面的代码初始化日期选择器后执行此操作:

$(this).datepicker("setDate", moment($(this).prev().val()).toDate());

Your best bet to set the defaultDate is to parse the value of the altField with a library like Moment.js, because browser implementations for parsing dates are unreliable. For example, if your altField is the field before your datepicker field and it's in ISO 8601 format, you can do this:

$(this).datepicker({
    altField: $(this).prev(),
    altFormat: $.datepicker.ISO_8601,
    defaultDate: moment($(this).prev().val()).toDate()
});

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:

$(this).datepicker("setDate", moment($(this).prev().val()).toDate());
私藏温柔 2025-01-01 12:08:10

不是 100% 优雅,因为它需要重复,但它对我有用:

$("#date-div").datepicker({altField:"#date-input",altFormat:"yy-mm-dd", defaultDate:$("#date-input").val()});

Not 100% elegant as it needs repetition but it works for me:

$("#date-div").datepicker({altField:"#date-input",altFormat:"yy-mm-dd", defaultDate:$("#date-input").val()});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文