给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
给定一个输入元素:
<input type="date" />
有没有办法将日期字段的默认值设置为今天的日期?
当前回答
这在一行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">
其他回答
由于日期类型只接受“yyyy-MM-dd”格式,因此需要相应地格式化日期值。
这是它的解,
var d = new Date();
var month = d.getMonth();
var month_actual = month + 1;
if (month_actual < 10) {
month_actual = "0"+month_actual;
}
var day_val = d.getDate();
if (day_val < 10) {
day_val = "0"+day_val;
}
document.getElementById("datepicker_id").value = d.getFullYear()+"-"+ month_actual +"-"+day_val;
我测试的最简单的工作版本:
< script src = " https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js " > < /脚本> <input type="date" id="date" name="date"> < >脚本 $(" #日期”)。瓦尔(新日期().toJSON () .slice (0, 10)); > < /脚本
即使过了这么久,这也能帮到别人。这是一个简单的JS解决方案。
JS
let date = new Date();
let today = date.toISOString().substr(0, 10);
//console.log("Today: ", today);//test
document.getElementById("form-container").innerHTML =
'<input type="date" name="myDate" value="' + today + '" >';//inject field
HTML
<form id="form-container"></form>
类似的解决方案也适用于Angular,无需任何额外的库来转换日期格式。对于Angular(由于通用组件代码,代码被缩短了):
//so in myComponent.ts
//Import.... @Component...etc...
date: Date = new Date();
today: String; //<- note String
//more const ...
export class MyComponent implements OnInit {
//constructor, etc....
ngOnInit() {
this.today = this.date.toISOString().substr(0, 10);
}
}
//so in component.html
<input type="date" [(ngModel)]="today" />
在HTML5中,没有办法将日期字段的默认值设置为今天的日期?如其他答案所示,可以使用JavaScript设置该值,如果希望根据页面加载时用户的当前日期设置默认值,这通常是最佳方法。
HTML5为input type=date元素定义了valueAsDate属性,使用它,你可以直接从创建的对象中设置初始值,例如new date()。然而,IE 10不知道这个属性。(它也缺乏对输入type=date的真正支持,但这是另一个问题。)
因此在实践中,您需要设置value属性,并且必须使用ISO 8601符号法。现在这很容易做到,因为我们可以期望当前使用的浏览器支持toISOString方法:
<input type=date id=e>
<script>
document.getElementById('e').value = new Date().toISOString().substring(0, 10);
</script>
JavaScript Date对象为所需的格式提供了足够的内置支持,以避免手动执行:
添加这个以获得正确的时区支持:
Date.prototype.toDateInputValue = (function() {
var local = new Date(this);
local.setMinutes(this.getMinutes() - this.getTimezoneOffset());
return local.toJSON().slice(0,10);
});
jQuery:
$(document).ready( function() {
$('#datePicker').val(new Date().toDateInputValue());
});
纯JS:
document.getElementById('datePicker').value = new Date().toDateInputValue();