javascript - 单击按钮时将时间戳传递给表单

标签 javascript html

Javascript 的新手。我想在用户单击按钮时将时间戳传递给表单,但我无法获取要提交的实际值。

<html>
<head>

<script type="text/javascript">
    var dateOfUser = new Date();
    document.getElementById("userdate").value = dateOfUser;
</script>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

// hide the content from user until they click the button
<script>
$(document).ready(function(){
  $("#show").click(function(){
     $("#ans").show();
    });
});
</script>

</head>
<body>

<p>
   Click the button to see the text.
</p>

<p><button type="button" id="show" onclick="userdate = new Date()">Show text</button></p>

<div id="ans" style="display:none">
<input type="hidden" id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text. 
</div>  

</body>

我省略了表单提交代码 - 遗憾的是我没有编写它,而且除了将其用于表单提交之外,我无权访问该代码。

但是提交后,.csv 文件包含:

"timestamp":"dateOfUser"

而不是“userdate”的值。据我所知,使用 document.getElementById("userdate").value = dateOfUser; 应该允许我在 HTML 中使用“userdate”。

任何帮助将不胜感激,我已经在此站点和其他站点上提出了许多类似的问题,但我无法弄清楚我做错了什么。

最佳答案

您可以删除 type="hidden" 进行测试。至少它适用于我使用 userdate.value

<html>
<head>
</head>
<body>

<p>
   Click the button to see the text.
</p>

<p><button type="button" id="show">Show text</button></p>

<div id="ans" style="display:none">
<input id="userdate" name="timestamp" value="dateOfUser">
Here is the hidden text. 
</div>  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>

// hide the content from user until they click the button
<script>
$(document).ready(function(){
  $("#show").click(function(){
     $("#ans").show();
     $("#userdate")[0].value = new Date()
    });
});
</script>
</body>

script 放在正文上方的方式

<script type="text/javascript">
    var dateOfUser = new Date();
    document.getElementById("userdate").value = dateOfUser;
</script>

不会工作,因为 dom(即元素)尚未加载。而onclick$(document).ready则与上述方式不同。

不过,还是把script放在body的底部比较好。

关于javascript - 单击按钮时将时间戳传递给表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57830560/

相关文章:

html - 如何在 Bootstrap 4 中首尾相连地显示 3 个相等的列

javascript - 如何使 vanilla Bootstrap 与 Node 上的 React 一起工作?

javascript - strip 化 IBAN 元素错误 'The type ` sepa_debit` 不是有效的源类型。

javascript - 避免多次删除事件

javascript - 如何从移动网页打开 Whatsapp 聊天?

javascript - 错误 : Unknown provider: translateFilterProvider <- translateFilter angularjs

html - DIV Contenteditable展开问题

php - 如何使用php隐藏一个div标签

html - html 表单开发的最佳实践是什么?

html - 如何使用 CSS 仅选择列表中成对的第一张图片?