如何重置bootstrap-datepicker的月份与年份?
Great question! I’ve dealt with this exact scenario when working with bootstrap-datepicker, so let’s break down the solutions based on how your picker is set up:
1. For Month/Year-Only Pickers
If you’ve configured your picker to only let users select months and years (e.g., using minViewMode: 1 or a date format like "yyyy-mm"), the cleanest way to clear the selected values is to use the official setDate API with null, then sync the UI with update:
$('#datepicker').datepicker('setDate', null).datepicker('update');
This will empty the input field and reset the picker’s dropdown view back to the default (usually the current month and year).
2. For Full Date Pickers
If you’re using a standard date picker (that includes day, month, and year) and want to completely clear all selected values (including month and year), your original approach works perfectly—but combining it with setDate(null) makes it more explicit and reliable across different picker versions:
$('#datepicker').val('').datepicker('setDate', null).datepicker('update');
If you’re looking for a more edge-case scenario—like resetting just the month/year while keeping the selected day—you’ll need to construct a new date object with the current month/year and the existing day value:
// Get the currently selected date const selectedDate = $('#datepicker').datepicker('getDate'); if (selectedDate) { // Create a new date with the same day, but current month/year const currentDate = new Date(); const resetDate = new Date(currentDate.getFullYear(), currentDate.getMonth(), selectedDate.getDate()); // Update the picker $('#datepicker').datepicker('setDate', resetDate).datepicker('update'); }
Bonus: Resetting the Picker View Without Clearing Input
If you just want to reset the picker’s dropdown view to the current month/year (but leave the input value untouched), use the setViewDate method:
$('#datepicker').datepicker('setViewDate', new Date());
内容的提问来源于stack exchange,提问作者ilce

