使用Pikaday插件为输入文本框赋值失败,求解决方案
Hey there, let's break down the issues with your code and get that datepicker working properly:
1. Duplicate Script Conflicts
You're loading both pickaday.js (the vanilla JS version) and pickaday.jquery.js (the jQuery wrapper) at the same time. These two files conflict with each other—pick one to keep (stick with the jQuery version if you're using jQuery elsewhere, or the vanilla version if not). Remove the redundant script tag to avoid unexpected behavior.
2. Manual Value Assignment is Unnecessary (and Causes Issues)
Your onSelect handler is manually setting the input's value, but Pikaday is designed to automatically update the linked field for you. When you override this manually, you can create inconsistencies between Pikaday's internal state and the input's value, which is likely why you're seeing [object Text] on refresh.
Instead, use Pikaday's built-in format option (it works seamlessly with Moment.js since you've loaded it) to define your desired date format. This lets Pikaday handle updating the input value correctly.
3. Incorrect Max Date Configuration
Months in JavaScript Date objects are 0-indexed (0 = January, 11 = December). Your maxDate: new Date(2020, 12, 31) actually creates a date in January 2021, not December 2020. Fix this by using 11 for December.
Corrected Code Example
Here's your revised script with all these fixes:
var picker = new Pikaday({ field: document.getElementById('datepicker'), firstDay: 1, minDate: new Date(2000, 0, 1), maxDate: new Date(2020, 11, 31), // Fixed month index yearRange: [2000, 2020], format: 'DD/MM/YYYY', // Let Pikaday handle formatting with Moment.js onSelect: function() { // No need to manually set input.value here—Pikaday does it for you! // If you want to do extra stuff on select, add it here: console.log("Selected date:", this.getMoment().format('DD/MM/YYYY')); } }); // Set initial date (note: dayOfYear(366) will jump to Jan 1 of the next year if the current year isn't a leap year) picker.setMoment(moment().dayOfYear(366));
Why This Works
- By using the
formatoption, Pikaday leverages Moment.js directly to format dates and update the input field consistently. - Removing duplicate scripts eliminates conflicts that might have been causing the
[object Text]display issue. - Fixing the max date ensures your date range is accurate.
If you still want to manually handle the value update for some reason (though it's not recommended), you can use this.getDate() instead of this.getMoment() and format it, but again, the built-in format is the cleaner approach.
内容的提问来源于stack exchange,提问作者user4963906

