简体   繁体   English

HTML 输入日期字段,如何设置默认值为今天的日期?

[英]HTML input date field, how to set default value to today's date?

I'm slightly confused as to why my JS script isn't working, I have set it up to populate the date field to today's date, but the HTML date picker is still showing dd/mm/yyyy by default.我对为什么我的 JS 脚本不起作用有点困惑,我已经将它设置为将日期字段填充为今天的日期,但 HTML 日期选择器默认情况下仍显示 dd/mm/yyyy。

my HTML is:我的 HTML 是:

<div class="col">
        <label for="date">Date</label>
        <input type="date" onload="getDate()" class="form-control" id="date" name="date">
</div>

my JS is:我的 JS 是:

function getDate(){
var today = new Date();

document.getElementById("date").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2);

}

 function getDate(){ var today = new Date(); document.getElementById("date").value = today.getFullYear() + '-' + ('0' + (today.getMonth() + 1)).slice(-2) + '-' + ('0' + today.getDate()).slice(-2); }
 <div class="col"> <label for="date">Date</label> <input type="date" onload="getDate()" class="form-control" id="date" name="date"> </div>

For input elements, the onload attribute is only supported when <input type="image">对于input元素,只有在<input type="image">时才支持onload属性

Tip: You use DOMContentLoaded for setting the default value提示:您使用DOMContentLoaded来设置默认值

<script>
    window.addEventListener('DOMContentLoaded', (event) => {
        document.getElementById("date").valueAsDate = new Date();
    });
</script>

Reference: https://www.w3schools.com/tags/att_onload.asp参考: https://www.w3schools.com/tags/att_onload.asp

I had some problems with that as well.我也有一些问题。 I arrived at:我到达:

document.getElementById('mydate').value = new Date().toISOString().substring(0, 10); document.getElementById('mydate').value = new Date().toISOString().substring(0, 10);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM