javascript - 如何在html中的输入文本框中打印日期

标签 javascript html

这是我的代码,我想在使用 onload 事件输入日期文本后在文本框中打印日期。

<!DOCTYPE html>
<html>
   <head>
      <script>
         function displayDate() {
            document.getElementById("fname").value = Date();
         }
      </script>
   </head>
   <body onload="displayDate()">
      Enter date: <input type="date" id="fname" readonly />
   </body>
</html>

最佳答案

你必须

  • 正确创建 Date 对象(您缺少 new)
  • 根据rfc3339格式化它(例如:2012/12/30)

改变

document.getElementById("fname").value = Date();

var now = new Date();
var formatedDate = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();​
document.getElementById("fname").value = formatedDate;

Demonstration

请注意,某些浏览器接受其他格式,但 Chrome 不接受,因为它符合 the norm .

关于javascript - 如何在html中的输入文本框中打印日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14092851/

相关文章:

html - 将一张图片放在另一张图片上

javascript - 设置 URL 以在 Django 模板中加载 iframe

Javascript Canvas 箭头 - 箭头不指向行尾

javascript - 在 codeIgniter 中使用单个表进行动态下拉

javascript - 用于禁用按钮的 jQuery 电子邮件验证脚本

php - 在 woocommerce 旁边添加图标添加到购物车按钮

javascript - 为什么使用对数给出 8e+2 值?

javascript - typescript + react : Element type is invalid: expected a string (for built-in components)

javascript - require ('bignumber.js' ) 在 truffle 测试中失败, npm ls -g 显示它已安装 (Windows)

jquery - css li 填充本身