给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
使用moment.js在2行中解决这个问题, html5日期输入类型只接受“YYYY-MM-DD”这种格式。我用这种方法解决问题。
var today = moment().format('YYYY-MM-DD');
$('#datePicker').val(today);
这是解决这个问题最简单的方法。
其他回答
$(document).ready(function(){
var date = new Date();
var day = ("0" + date.getDate()).slice(-2); var month = ("0" + (date.getMonth() + 1)).slice(-2);
var today = date.getFullYear()+"-"+(month)+"-"+(day) ;
});
$('#dateid').val(today);
与任何HTML输入字段一样,浏览器将date元素保留为空,除非在value属性中指定了默认值。不幸的是,HTML5没有提供在htmlputelelement .prototype.value中指定“today”的方法。
相反,必须显式提供RFC3339格式的日期(YYYY-MM-DD)。例如:
element.value = "2011-09-29"
这在一行JS中是可能的。
HTML:
<input type="date" id="theDate">
JS:
document.getElementById('theDate').value = new Date().toISOString().substring(0, 10);
. getelementbyid(“theDate”)。value = new Date(). toisostring()。substring (0, 10); <input type="date" id="theDate">
来匹配原始查询。
date.value = new Date().toJSON().split('T')[0] <输入类型=“日期” id=“日期”/>
对于那些使用ASP VBScript的人
<%
'Generates date in yyyy-mm-dd format
Function GetFormattedDate(setDate)
strDate = CDate(setDate)
strDay = DatePart("d", strDate)
strMonth = DatePart("m", strDate)
strYear = DatePart("yyyy", strDate)
If strDay < 10 Then
strDay = "0" & strDay
End If
If strMonth < 10 Then
strMonth = "0" & strMonth
End If
GetFormattedDate = strYear & "-" & strMonth & "-" & strDay
End Function
%>
然后在body中,元素应该是这样的
<input name="today" type="date" value="<%= GetFormattedDate(now) %>" />
干杯!