如何将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
onSelectcallback fires immediately when a user picks a date in#outDate, passing the formatted date string as an argument. - We fetch the instance of the
#returnDatepicker usingdatepicker('instance')—this lets us access its internal methods likesetDate. setDateaccepts either a formatted string (matching your picker’sformatsetting) or a native JavaScriptDateobject, so it works seamlessly with the value fromonSelect.
内容的提问来源于stack exchange,提问作者Chuck Villavicencio
相关产品推荐
相关产品推荐

