如何动态限制jQuery下拉框仅显示当前及上月并默认选中当月
Solution to Show Only Current and Previous Month in Dropdown
Hey there! Let's adjust your code to achieve exactly what you want: displaying only the current month and the previous one in your dropdown, with the current month selected by default. Here's how to do it step by step:
First, Let's Fix the Core Logic
Your original code disables future months, but we need to remove or hide all months except the current and previous one, while ensuring the current month stays selected. Also, note that JavaScript's getMonth() returns a 0-based index (0 = January, 11 = December), which aligns perfectly with your dropdown option indices.
Complete Working Code
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div> <select id="monthsDropdown"> <option value='1'>January</option> <!-- Fixed the typo "Janaury" --> <option value='2'>February</option> <option value='3'>March</option> <option value='4'>April</option> <option value='5'>May</option> <option value='6'>June</option> <option value='7'>July</option> <option value='8'>August</option> <option value='9'>September</option> <option value='10'>October</option> <option value='11'>November</option> <option value='12'>December</option> </select> </div> <script> $(document).ready(function() { var currentDate = new Date(); var curMonthIndex = currentDate.getMonth(); // 0 = Jan, 11 = Dec // Calculate previous month index (handle January → December case) var prevMonthIndex = curMonthIndex === 0 ? 11 : curMonthIndex - 1; // 1. Set current month as selected first $('#monthsDropdown option').eq(curMonthIndex).prop('selected', true); // 2. Remove all options except current and previous month // Use .hide() instead of .remove() if you want to keep them in DOM but hidden $('#monthsDropdown option').not(':eq(' + curMonthIndex + '), :eq(' + prevMonthIndex + ')').remove(); }); </script>
Key Explanations
- Boundary Case Handling: When the current month is January (index 0), we set the previous month index to 11 (December) so we don't get a negative number.
- Select First, Remove Later: We set the current month as selected before removing other options to ensure the selection doesn't break after modifying the dropdown.
- Remove vs Hide: Use
.remove()to completely delete unwanted options from the DOM, or.hide()if you might need to restore them later (they'll be invisible but still present in the HTML).
Example Behavior
- If today is in June (index 5): The dropdown will show May (index4) and June (index5), with June selected.
- If today is in January (index0): The dropdown will show December (index11) and January (index0), with January selected.
内容的提问来源于stack exchange,提问作者Jain Prince




