如何限制 jquery 下拉列表并动态仅显示当前和前几个月

我试图在下拉列表中仅显示当前和上个月,并想从下拉列表中隐藏/删除其他月份。此外,默认选择应该是 - 到当月

使用下面的代码我可以实现 -

  • 在下拉菜单中显示月份

  • 默认选择为当月

  • 禁用接下来的几个月

我在寻找:

  • 默认选择为当月

  • 在下拉列表中只显示上个月

任何人都可以请帮助或指导。提前致谢!!

代码:

$(document).ready(function() {

  debugger;

  var currentDate = new Date();

  var curMonth = currentDate.getMonth();

  $('#monthsDropdown').prop('selectedIndex', curMonth);

  $('#monthsDropdown option:gt(' + curMonth + ')').prop('disabled', true);

});

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div>

  <select id="monthsDropdown">

    <option value='1'>Janaury</option>

    <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>


梵蒂冈之花
浏览 155回答 3
3回答

拉莫斯之舞

$(document).ready(function(){&nbsp;var objMonthMapping = {&nbsp; 1&nbsp; &nbsp; &nbsp;: 'January',&nbsp; 2&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'February',&nbsp; 3&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'March',&nbsp; 4&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'April',&nbsp; 5&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'May',&nbsp; 6&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'June',&nbsp; 7&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'July',&nbsp; 8&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'August',&nbsp; 9&nbsp; &nbsp; &nbsp;:&nbsp; &nbsp;'September',&nbsp; 10&nbsp; &nbsp; :&nbsp; &nbsp;'October',&nbsp; 11&nbsp; &nbsp; :&nbsp; &nbsp;'November',&nbsp; 12&nbsp; &nbsp; :&nbsp; &nbsp;'December'};var intCurMonth&nbsp; &nbsp; &nbsp;=&nbsp; &nbsp;new Date().getMonth() + 1;var intPrevMonth&nbsp; &nbsp; =&nbsp; &nbsp;(intCurMonth - 1) ? (intCurMonth - 1) : 12;$('<option>').val(intPrevMonth).text(objMonthMapping[intPrevMonth]).appendTo('#monthsDropdown');$('<option>').val(intCurMonth).text(objMonthMapping[intCurMonth]).appendTo('#monthsDropdown');$('#monthsDropdown').val(intCurMonth);});这是 HTML:<div>&nbsp; &nbsp;<select id="monthsDropdown">&nbsp; &nbsp;</select></div>这些代码行将在下拉列表中提供当前月份和上个月的选项。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript