-2

I have a button that I want to set time but for the function I have to define it on the body element for the code to run , it works perfect with plain js but throwing an error when I use jQuery

<body onload="startTime()">
<input type="text" id="timer">

$(document).ready(function(){
function startTime(){
     var  date = new Date();
     var h = date.getHours();
     var m = date.getMinutes();
      var  s = date.getSeconds();
     $('#timer').val(h + ':' + m + ':' + s);
var t = setTimeout(startTime, 500);
}
}); 

**well, I dont think I did anything wrong there but console is giving undefined startTime at index.html **

I don't know whether defining the body onload inside the ready function or what? Please help me...Am new to jQuery and don't know how to fix this

Nancy256
  • 43
  • 7

2 Answers2

-1

Either define the function globally (outside the ready) or get rid of onload and call the function inside ready. Also note it is new Date not new date

$(document).ready(function() {
  function startTime() {
    var date = new Date();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    $('#timer').val(h + ':' + m + ':' + s);
    var t = setTimeout(startTime, 500);
  }

  startTime();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="timer">
charlietfl
  • 164,229
  • 13
  • 110
  • 143
-1

Now You can also use

$(function () {
  //Your code or methods
});

So your code will be

$(function(){
  startTime();
});

 function startTime() {
    var date = new Date();
    var h = date.getHours();
    var m = date.getMinutes();
    var s = date.getSeconds();
    $('#timer').val(h + ':' + m + ':' + s);
    var t = setTimeout(startTime, 500);
  }