How to set value of an input field using jQuery

Viewed 12654

I want to show current time within input field. I have used 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>
3 Answers

Simply Edit the script: change html to 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.

Have a look at this for the uses of .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;  
}
Related