【问题标题】:Saving gettime to form field将 gettime 保存到表单字段
【发布时间】:2023-03-22 05:56:01
【问题描述】:

我是一个相对的 JS 新手,但我有点麻烦 - 对于表单提交系统,我需要使用唯一 ID 填充表单字段(可以是任何东西,只要它相对确定是独一无二的)。

我考虑过使用 getTime(),因为它会产生一个足够长且唯一的数字来满足我的要求。但我似乎无法理解使用此值填充常规(隐藏)文本字段所需的代码,尽管关于 SO 的几个主题提出了类似的问题。

表单和所有 HTML 都已经到位,我只需要 js 脚本。谁能帮帮我?

【问题讨论】:

  • 您能提供到目前为止您编写的任何代码吗?
  • 试试this
  • 我现在在家,但根据记忆,它类似于:var d = new Date(); var n = d.getTime(); document.getElementsbyName("MyFormField").value = n; 然后表单输入的名称将是 MyFormField。

标签: javascript forms input gettime


【解决方案1】:
var timestamp = new Date().getUTCMilliseconds();


var now = new Date(); 
timestamp =now.getFullYear().toString(); 
// 2011
timestamp += (now.getFullMonth < 9 ? '0' : '') + now.getFullMonth().toString();
 // JS months are 0-based, so +1 and pad with 0's
 timestamp += (now.getDate < 10) ? '0' : '') + now.getDate().toString(); 

然后将该时间戳附加到您的输入中

<input name="timestamp" id="input" type="hidden"/>

然后:

document.querySelector('#input').value = timestamp;

编辑:最终代码

<script>
     document.onreadystatechange = function()
     {
          if(document.readyState == "interactive")
          {
                     var now = new Date(); 
timestamp =now.getFullYear().toString(); 
// 2011
timestamp += (now.getFullMonth < 9 ? '0' : '') + now.getFullMonth().toString();
 // JS months are 0-based, so +1 and pad with 0's
 timestamp += (now.getDate < 10) ? '0' : '') + now.getDate().toString(); 

               document.querySelector('#input').value = timestamp;
          }
     }
</script>

将此脚本标签放在文档的底部。

【讨论】:

  • 嗯,它似乎不起作用。我是否在表单之前添加第一个脚本,然后是表单,然后是表单之后的第二个脚本?
  • 谢谢,这似乎解决了它! :-)
猜你喜欢
  • 2021-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多