简体   繁体   中英

Auto Refresh Input Time object without reloading page

I have an input field that I would like to refresh every 2 seconds or so. However,I can't seem to get the 'setInterval' right because it is not updating my ID. Should I not be using the ID to declare the refresh? Any help will be most appreciated.

<!DOCTYPE html>
<html>
   <head>
      <meta charset="UTF-8" content="HTML,CSS,XML,JavaScript">
      <script src="Scripts/Global.js" type="text/javascript"></script>
      <script src="Scripts/jquery.js" type="text/javascript"></script>    
      <link rel="stylesheet" type="text/css" href="Styles/Design.css">
   </head>
   <body>
      Time: &nbsp;<input type="time" id="theTime">
      <script type="text/javascript"
         src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
      <script>
         var myVar = setInterval(function(){ myTimer() }, 1000);

         function myTimer() {
            var d = new Date();
            var t = d.toLocaleTimeString();
            document.getElementById("theTime").innerHTML = t;
         }
      </script>
      <script type="text/javascript">
         $(document).ready( function() {
                            var now = new Date();
                            //now2 prevents the milliseconds from showing up in the input
                            var now2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()-8, now.getMinutes(), now.getSeconds());
                            $('#theTime')[0].valueAsDate = now2;
                        });

      </script>
    </body>
</html>

You're setting the innerHTML of myTimer, where you should really be setting the valueAsDate , like in your $(document).ready function.

Here's how myTimer should look:

function myTimer() {
   var now = new Date();
   var now2 = new Date(now.getFullYear(), now.getMonth(), now.getDate(), now.getHours()-8, now.getMinutes(), now.getSeconds());
   $('#theTime')[0].valueAsDate = now2;
}

and then you can call myTimer() from within your $(document).ready :

$(document).ready( function() { 
  myTimer();
});

you are trying to set the innerHTML of an input field. use $('#theTime').val() instead!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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