javascript 如何通过单击按钮将日期和时间插入输入字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10098038/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I Insert date and time into input field via a button click
提问by Erik
I need a script that will insert the current date and time in an input field via a button click? Can anyone refer me to a script?
我需要一个脚本来通过单击按钮在输入字段中插入当前日期和时间?谁能给我推荐一个脚本?
I prefer jquery or ajax or javascript.
我更喜欢 jquery 或 ajax 或 javascript。
Many thanks.
非常感谢。
回答by alxbrd
jQuery:
jQuery:
$(
function(){
$('#time').click(function(){
var time = new Date();
$('#time-holder').val(time.toDateString());
});
}
);
HTML:
HTML:
<input type="text" value="" id="time-holder">
<input type="button" value="time" name="timer" id="time">
Here is a jsFiddle example.
这是一个jsFiddle 示例。
回答by RobG
A simple implementation:
一个简单的实现:
<form>
<input name="theDate" size="50">
<input type="button" value="Insert date" onclick="
this.form.theDate.value = new Date();
">
</form>
回答by joshuahealy
Something like this should do the trick:
像这样的事情应该可以解决问题:
$('#yourButtonId').click(function() {
var now = new Date();
$('#yourInputId').val(now.toDateString());
});
回答by ahruss
With JavaScript, you can use the Date object. To change the input's value when you click on a button, you could do something like this:
通过 JavaScript,您可以使用 Date 对象。要在单击按钮时更改输入值,可以执行以下操作:
document.getElementById("buttonId").onclick = function() {
var date = new Date();
document.getElementById("inputId").value = date.toString();
};
Or, if you only want to use part of the date or to format it another way, you can get the specific attributes of the object with functions like date.getDate()
, date.getFullYear()
, etc., and replace date.toString()
with whatever format you want there. There's a full list of the Date object's methods at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
或者,如果你只是想使用日期的一部分,或将其格式化另一种方式,你可以得到类似的功能对象的特定属性date.getDate()
,date.getFullYear()
等等,并更换date.toString()
有任何格式你想在那里。在https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date上有 Date 对象的方法的完整列表