如何为jQuery DCalendar插件设置初始选中日期
Hey there! I've worked with this exact calendar plugin before, so let's get your pre-filled date automatically selected on page load. Here's the straightforward fix:
Solution 1: Pass the Default Date During Initialization
The simplest way is to initialize the calendar while specifying your pre-existing date as the default selected value. Since your pageDate is already in the plugin's expected mm/dd/yyyy format, this will work seamlessly:
$(document).ready(function() { var pageDate = "4/04/2018"; // Set the input value AND initialize the calendar with the target date $('.date').val(pageDate).dcalendar({ date: pageDate // This tells the plugin to select this date on load }); });
Solution 2: Update Selection If Calendar Is Already Initialized
If your calendar is initialized elsewhere in your code (before setting the input value), you can manually trigger the selection after setting the input's value:
$(document).ready(function() { var pageDate = "4/04/2018"; var $dateInput = $('.date'); // Set the input value first $dateInput.val(pageDate); // Initialize the calendar if it hasn't been already if (!$dateInput.data('dcalendar')) { $dateInput.dcalendar(); } // Get the calendar instance and select the target date var calendarInstance = $dateInput.data('dcalendar'); var targetDate = new Date(pageDate); calendarInstance.selectDate(targetDate); });
Key Notes:
- Make sure your date format (
mm/dd/yyyy) matches the plugin's default format. If you're using a different format, add theformatoption to thedcalendar()initialization (e.g.,format: 'dd/mm/yyyy'). - Always wrap your code in
$(document).ready()to ensure the DOM is fully loaded before manipulating elements or initializing plugins.
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

