You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Materialize中第一个日期选择器的选中日期设置到第二个?

Solution for Syncing Materialize Date Pickers

No worries, this is a common use case that’s totally solvable with Materialize’s datepicker API (even if it’s not super prominent in the docs!). Here’s how to link your #outDate and #returnDate pickers:

Step 1: Optimize Initialization & Add Sync Logic

First, let’s clean up your code (no need for two separate $(document).ready() calls) and add the sync functionality using Materialize’s built-in onSelect callback and setDate method:

$(document).ready(function(){
  // Initialize departure date picker with sync logic
  $('#outDate').datepicker({
    format: 'dd-mm-yyyy',
    // Triggered when a date is selected
    onSelect: function(selectedDate) {
      // Get the instance of the return date picker
      const returnPickerInstance = $('#returnDate').datepicker('instance');
      
      // Set the selected date to the return picker
      returnPickerInstance.setDate(selectedDate);
    }
  });

  // Initialize return date picker
  $('#returnDate').datepicker({
    format: 'dd-mm-yyyy'
  });
});

Step 2: (Optional) Add Date Validation

To make this more user-friendly, you can also set the minimum selectable date for #returnDate to match the selected #outDate (so users can’t pick a return date earlier than their departure date):

$(document).ready(function(){
  $('#outDate').datepicker({
    format: 'dd-mm-yyyy',
    onSelect: function(selectedDate) {
      const returnPickerInstance = $('#returnDate').datepicker('instance');
      
      // Convert the formatted date string to a Date object (Materialize uses 0-indexed months)
      const [day, month, year] = selectedDate.split('-');
      const parsedDate = new Date(year, month - 1, day);
      
      // Set the return date and enforce minimum date
      returnPickerInstance.setDate(selectedDate);
      returnPickerInstance.options.minDate = parsedDate;
    }
  });

  $('#returnDate').datepicker({
    format: 'dd-mm-yyyy'
  });
});

How This Works:

  • The onSelect callback fires immediately when a user picks a date in #outDate, passing the formatted date string as an argument.
  • We fetch the instance of the #returnDate picker using datepicker('instance')—this lets us access its internal methods like setDate.
  • setDate accepts either a formatted string (matching your picker’s format setting) or a native JavaScript Date object, so it works seamlessly with the value from onSelect.

内容的提问来源于stack exchange,提问作者Chuck Villavicencio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:22:40