Javascript 如何在实现日期选择器中设置日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30324552/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:59:54  来源:igfitidea点击:

How to set the date in materialize datepicker

javascriptjquerydatepickermaterial-design

提问by Anup

I am using materializecss.com Datepicker. When i try to set date with jquery, the date doesn't get set. Here is my Code :-

我正在使用 materializecss.com 日期选择器。当我尝试使用 jquery 设置日期时,未设置日期。这是我的代码:-

// Materialize Date Picker
    window.picker = $('.datepicker').pickadate({
        selectMonths: true, // Creates a dropdown to control month
        selectYears: 100, // Creates a dropdown of 15 years to control year
        format: 'dd/mm/yyyy'    
    });

<input type="text" id="Date" class="datepicker" />

On Click event of a Button , I am setting the date :-

在 Button 的 Click 事件上,我正在设置日期:-

$("#Date").val('23/01/2015');

When i open the datepicker it shows me today's date.

当我打开日期选择器时,它会显示我今天的日期。

How to set the date in materialize datepicker?

如何在实现日期选择器中设置日期?

回答by art-solopov

Materialize datepicker is a modified pickadate.jspicker.

Materialize datepicker是一个修改过的pickadate.js选择器。

Accodging to their API docs, this is how to set the picker:

根据他们的API 文档,这是设置选择器的方法:

  1. Get the picker:
  1. 获取选择器:

var $input = $('.datepicker').pickadate()

// Use the picker object directly.
var picker = $input.pickadate('picker')

  1. Set the date:
  1. 设置日期:

// Using arrays formatted as [YEAR, MONTH, DATE].
picker.set('select', [2015, 3, 20])

// Using JavaScript Date objects.
picker.set('select', new Date(2015, 3, 30))

// Using positive integers as UNIX timestamps.
picker.set('select', 1429970887654)

// Using a string along with the parsing format (defaults to `format` option).
picker.set('select', '2016-04-20', { format: 'yyyy-mm-dd' })

回答by Gabriel

just add the format you want your date looks like in the attributes of your element.

只需在元素的属性中添加您希望日期的格式即可。

$('.datepicker').pickadate({
    selectMonths: true, // Creates a dropdown to control month
    selectYears: 15, // Creates a dropdown of 15 years to control year
    format: 'dd-mm-yyyy' });

回答by Germa Vinsmoke

You can use methods of datepicker which are present in V1.0.0-rc.2.

您可以使用存在于V1.0.0-rc.2.

<script>
    document.addEventListener('DOMContentLoaded', function () {
        var options = {
            defaultDate: new Date(2018, 1, 3),
            setDefaultDate: true
        };
        var elems = document.querySelector('.datepicker');
        var instance = M.Datepicker.init(elems, options);
        // instance.open();
        instance.setDate(new Date(2018, 2, 8));
    });
</script>

defaultDatewill set a default Date that will be shown in input-field of datepicker without even opening the picker.

defaultDate将设置一个默认日期,该日期将显示在日期选择器的输入字段中,甚至无需打开选择器。

enter image description here

在此处输入图片说明

instance.setDate()will select the date in datepicker when you'll open it.

instance.setDate()当您打开它时,将在 datepicker 中选择日期。

enter image description here

在此处输入图片说明

Note-new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

笔记-new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);

The argument monthIndexis 0-based. This means that January = 0and December = 11

参数monthIndex是基于 0 的。这意味着January = 0December = 11

Picker - Materialize

选择器 - 物化

MDN - Date

MDN - 日期

回答by hendrikbeck

Alle answers with pickadate() don't work anymore in newer versions of Materialize. The method is now named datepicker(). Here's my code snippet:

使用 pickadate() 的所有答案在较新版本的 Materialise 中不再有效。该方法现在被命名为 datepicker()。这是我的代码片段:

var element = document.querySelector('.datepicker');
M.Datepicker.getInstance(element).setDate(new Date(2018,8,7), true);

回答by Agustin

You can pass in the options that you want to default to on init. For example the below js code would work with markup:

您可以传入您希望在初始化时默认使用的选项。例如,下面的 js 代码可以使用标记:

const elems2 = document.querySelectorAll('.datepicker');
  for (element of elems2) {
    const date = element.dataset.defaultDate
    if (date !== undefined) {
      M.Datepicker.init(element, {defaultDate: new Date(date), yearRange: 15})
    }
    else {
       M.Datepicker.init(element, {})
    }
  }
<!-- Compiled and minified CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

    <!-- Compiled and minified JavaScript -->
    <script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
           
           
           
         <input class="validate datepicker valid" required="required" data-default-date="2009-07-11 10:14:47 -0700" name='picker' type="text">
         <label for="picker" class="active">Date Picker 10 years ago</label>

回答by David Corral

If you are using angular, or something similar, in order to manage your web application and you are not able to instance the Datepickerobject, according to the materializedocumentation, using jQueryyou can refer to these methods of the object:

如果您正在使用angular或类似的东西来管理您的 Web 应用程序并且您无法实例化Datepicker对象,根据具体文档,使用jQuery您可以参考对象的这些方法:

$('.datepicker').datepicker('setDate', new Date());

In the first parameter, in this case setDate, you may specify the method name that you are about to use. In the second parameter, in this case new Date(), you will pass the value to the function (if any).

在本例中的第一个参数中setDate,您可以指定将要使用的方法名称。在第二个参数中,在本例中new Date(),您将把值传递给函数(如果有)。

In the example, that line will update the date of all datepickers with the class .datepickerto today.

在示例中,该行会将所有具有该类的日期选择器的日期更新.datepicker为今天。

回答by Shinto Joseph

As per the docs materializecss.comCheck the Date format options.

根据文档materializecss.com检查日期格式选项。

// date picker
$(document).ready(function(){

  $('.datepicker').datepicker( {"format":'dd-mm-yyyy'} ).datepicker("setDate", new Date());

});

You can remove and change the code to below if you do not need current date as highlighted in calendar,

如果您不需要日历中突出显示的当前日期,则可以删除并将代码更改为以下代码,

// date picker
$(document).ready(function(){

  $('.datepicker').datepicker( {"format":'dd-mm-yyyy'});

});

回答by sowmya

var $input = $('.datepicker').pickadate()

// Use the picker object directly.
var picker = $input.pickadate('picker')

Heading

标题

回答by Syahmi Yusoff

$('#elementID').pickadate('picker').set('select', '21/05/2017', { format: 'dd/mm/yyyy' }).trigger("change");

This should suit your needs in one line. Trigger change you may need or maybe not, depends your situation, like me i need it for validation to trigger. Also include with format date just in case some people need it.

这应该在一行中满足您的需求。您可能需要或不需要触发更改,取决于您的情况,像我一样,我需要它进行验证才能触发。还包括格式日期,以防万一有人需要它。

回答by Salvatore Fiengo

watch out for your css and js version of materialize: if in the <head>you have

注意你的 css 和 js 版本的 materialize:如果<head>你有

<link rel="stylesheet"  href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.100.2/css/materialize.min.css">

then stick to it having same JS version so that you can use $('.datepicker').pickadate('picker').set('select','your parsed date',{format:'your format'}).trigger('change')

然后坚持使用相同的 JS 版本,以便您可以使用 $('.datepicker').pickadate('picker').set('select','your parsed date',{format:'your format'}).trigger('change')

If version is 1.0.0 then you will have to use $('.datepicker').datepicker();

如果版本是 1.0.0 那么你将不得不使用 $('.datepicker').datepicker();