【问题标题】:How can I change my date picker into a year only picker?如何将我的日期选择器更改为仅一年的选择器?
【发布时间】:2023-04-11 02:25:01
【问题描述】:

我只想在动态输入字段中更改年份选择器日历。日历应该只显示年份值谁能帮帮我。

这里是javascript代码。

$('body').on('focus',".datepicker", function(){

    if( $(this).hasClass('hasDatepicker') === false )  {
        $(this).datepicker();
    }

});

【问题讨论】:

  • 您使用的是哪个日期选择器库?
  • 日期选择器将是这项任务的巨大开销。只需使用从 19xx 年到 20xx 年的数字列表进行下拉
  • 类似,它工作得很好,但它显示日期、月份和年份日历。但对我来说,我只想显示年份。如果你能帮助我,我会很高兴的。

标签: javascript jquery html


【解决方案1】:

你可以试试这个。看看它是否能解决你的问题。

HTML:

<select name="yearpicker" id="yearpicker"></select>

JS:

var startYear = 1800;
for (i = new Date().getFullYear(); i > startYear; i--)
{
  $('#yearpicker').append($('<option />').val(i).html(i));
}

这是一个 jsfiddle link

【讨论】:

    【解决方案2】:

     $('body').on('focus',".datepicker", function(){
        if( $(this).hasClass('hasDatepicker') === false )  {
            $(this).datepicker({
                minViewMode: 2,
                format: 'yyyy'
            });
        }
    });
    <script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/css/bootstrap-datepicker.css" rel="stylesheet">
        <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datepicker/1.5.0/js/bootstrap-datepicker.js"></script>
    <input type="text" class="datepicker" />

    我认为它是引导日期选择器 (Link)

    【讨论】:

    • 它无法工作。当我注释掉日期格式时,它会带来包括月份、日期和年份在内的日历。当我采用年份格式时,它不起作用。请帮助我
    • @n.ssendawula 你可以在我的帖子中找到上面的运行示例。
    • 您的代码在单独的文件中运行得非常好,但是当我将它粘贴到我的脚本中时,它没有。我怎样才能让它工作?可能是什么原因导致这种失败。我需要一些帮助
    • 非常感谢。现在它工作正常。我已经解决了这个问题。祝你有美好的一天
    • 我想帮我做点什么,如何将最大年份设置为当前年份。谢谢
    【解决方案3】:

    如果您想只选择一年,我不会使用datepicker。为此使用select。但是,您可以修改datepicker(因为您没有提及您使用的是哪一个,所以我假设 jQuery UI)只返回年份

    看看这个小提琴:

    $(function() { 
        $(".datepicker").datepicker({ dateFormat: 'yy' });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.9.1/themes/base/jquery-ui.css" />
    <script src="https://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
    
    <input type="text" class="datepicker"/>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      • 1970-01-01
      • 2012-01-26
      • 1970-01-01
      • 1970-01-01
      • 2016-02-03
      • 1970-01-01
      相关资源
      最近更新 更多