使用Javascript预填充日期输入字段 [英] pre-populating date input field with Javascript

查看:203
本文介绍了使用Javascript预填充日期输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将一个日期预填入htmldate输入字段,但它忽略了我尝试传递的值:

I am trying to prepopulate a date into an html "date" input field, but it ignores the values I try to pass:

<html>
...
<input id='date' type='date'>
...
</html>

<script>
...
var myDate = new Date();
$("#date").val(myDate);
...

我也尝试将日期对象作为字符串传递

I have also tried passing the date object as a string

var myDate = new Date().toDateString();
$("#date").val(myDate);

当我打开表单时,日期字段为空。如果我消除type =date标签,该值将显示为一个字符串,但是我没有访问datepicker的权限。如何预先填充日期输入并仍然使用datepicker?我被困了。

When I open the form, the date field is blank. If I eliminate the type="date" tag, the value shows up as a string, but then I don't have access to the datepicker. How do I pre-populate a date input and still have use of the datepicker? I'm stumped.

谢谢。

推荐答案

设置为ISO格式。

(function () {
    var date = new Date().toISOString().substring(0, 10),
        field = document.querySelector('#date');
    field.value = date;
    console.log(field.value);

})()

http://jsfiddle.net/GZ46K/

这篇关于使用Javascript预填充日期输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆