简体   繁体   English

如何使用jQuery设置输入字段的值

[英]How to set value of an input field using jQuery

I want to show current time within input field. 我想在输入字段中显示当前时间。 I have used id local-time . 我已经使用id local-time But in the input field, current time is not showing. 但是在输入字段中,没有显示当前时间。

Current Time : <input type="text" id = "local-time" value= ""/>
<script>
setInterval(function() {
var local = new Date();
var localdatetime = local.getHours() + ":" + pad(local.getMinutes()) + ":" + 
pad(local.getSeconds());

$('#local-time').html(localdatetime);
}, 1000);

function pad(t) {
var st = "" + t;

while (st.length < 2)
st = "0" + st;

return st;  
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Simply Edit the script: change html to val 只需编辑脚本:将html更改为val

<script>
setInterval(function() {
var local = new Date();
var localdatetime = local.getHours() + ":" + pad(local.getMinutes()) + ":" + 
pad(local.getSeconds());

$('#local-time').val(localdatetime);
}, 1000);

function pad(t) {
var st = "" + t;

while (st.length < 2)
st = "0" + st;

return st;  
}
</script>

You tried to set the html instead of value of that input element. 您试图设置html而不是该输入元素的value

Have a look at this for the uses of .val() .html() .text() 有一个看看这个对的用途.val() .html() .text()

$('#local-time').val(localdatetime);
setInterval(function() {
  var local = new Date();
  var localdatetime = local.getHours() + ":" + pad(local.getMinutes()) + ":" + 
  pad(local.getSeconds());

  $('#local-time').val(localdatetime);
}, 1000);

function pad(t) {
   var st = "" + t;

   while (st.length < 2)
   st = "0" + st;

   return st;  
}

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

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