【问题标题】:Set a maximum year in datepicker jquery在 datepicker jquery 中设置最大年份
【发布时间】:2019-09-26 17:06:52
【问题描述】:

我有以下代码

<script>
        $(document).ready(function() {
            $(".datepicker").datepicker( {
        year = today.getFullYear,
        format: " yyyy", // Notice the Extra space at the beginning
        viewMode: "years", 
        minViewMode: "years",
        yearRange: '1920 : year',
        autoclose: true,            
        });
        });
    </script>

如你所见,我只需要年份,但我不想选择接下来的年份...我的意思是 2020 年、2021 年、2022 年...甚至应该无法选择...我看了周围但找不到解决方案,有人可以帮我吗?谢谢

编辑:

<script>
$(document).ready(function() {
  $('#datepicker').keyup(function() {

    var inputVal = $(this).val();
    var dateReg = /^\d{4}$/;

    if (dateReg.test(inputVal)) {
      $("#datemsg").html("Valid").css("color", "green");
    } else {

      $("#datemsg").html("Invalid date").css("color", "red");
    }
  });

  $("#datepicker").datepicker({
    format: " yyyy", // Notice the Extra space at the beginning
    viewMode: "years",
    minViewMode: "years",
    autoclose: true,
    endDate: new Date(),
  });
});
</script>

【问题讨论】:

  • 您不能将变量赋值放在对象中。
  • 您似乎在 jQuery UI 和 Bootstrap Datepickers 之间混合使用选项。 Bootstrap 没有yearRange 选项,文档是here
  • 也没有viewMode 选项,只有minViewModemaxViewMode
  • 每个帖子一个问题。这个问题是关于设置最大年份的,正则表达式与它有什么关系?
  • 为什么不禁用手动输入而只使用日期选择器?这样他们就不能输入任何无效的内容。

标签: javascript jquery datepicker bootstrap-datepicker


【解决方案1】:

你需要将year连接到你的范围字符串,因为js不会解析这个变量:

    year = today.getFullYear,
    $(".datepicker").datepicker({
        format: " yyyy", // Notice the Extra space at the beginning
        viewMode: "years", 
        minViewMode: "years",
        yearRange: '1920 : ' + year,
        autoclose: true,            
     });

【讨论】:

  • 虽然此代码 sn-p 可能是解决方案,但 including an explanation 确实有助于提高您的帖子质量。请记住,您是在为将来的读者回答问题,而这些人可能不知道您提出代码建议的原因。
  • @nircraft 有另一个解释的答案,所以我没有退出我的,直到其他被接受。然后这个问题进行了长时间的讨论,Barmar 删除了他的回答。我将添加一些细节,但这在这种情况下似乎并不重要。感谢您的关注:)
猜你喜欢
  • 2017-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-13
相关资源
最近更新 更多