var server_time=document.getElementById('sys_time');
var server_time=document.getElementsByTagName('p');
var server_time=document.childNodes[0];
// If it works the alert below will display the static time
alert(+server_time);
I’m using the alert to confirm if I’ve managed to get the time ok from the html, it should when working display the static time but currently displays NaN which AFAIK means that javascript is getting something from the HTML but it’s in a form that it can’t work with.
I know that the HTML validates fine, the time display is output from PHP. The intention is that PHP will output the time, if javascript is available then the javascript will take the static time and turn it into a ticking clock.
I’ll look into the main guts of the clock script at another time, right now I need to get the basics working. I need to do it something like this way as I don’t want to have any javascript embeded in the HTML, I want to have the javascript in external files.
Am I going in the right direction? It’s probably something simple (hopefully) that I’m doing wrong.
You need to make your incoming string part of a Date object. The following script does that and returns the time component of the new Date object. The full input requires the year, month and day as well, so I have taken these from the time when the page loads.
You will notice that I have moved the id “sys_time” down to the p element because we want the innerHTML of the <p>, not the <div>.
<title>Javascript Clock</title>
<meta http-equiv=“Content-Type” content=“text/html; charset=utf-8” />
<script type=“text/javascript”>
<!–
function init()
{ // get time string from page
var server_time=document.getElementById(‘sys_time’);
server_time=server_time.innerHTML;
// get the current time
var nowTime= new Date()
// use the date part of the string to build date format string
// uses static method of Date object to parse string
// return milliseconds
var inString=Date.parse(nowTime.toDateString()+“,”+server_time);
// use these milliseconds to create new date object
var thisTime=new Date(inString);
// show time component of date object produced
alert(thisTime.toLocaleTimeString())
}
//–>
</script>
</head>
<body onload=“init()”>
<div>
<p id=“sys_time”>12:47:09</div>
<!-- end sys_time –>
I’m having trouble getting a text string into a variable:
Either I am misunderstanding something here or we are grossly over-sciencing simething pretty basic. If all you have is a text string inside a div and you want to transfer the text string to a js variable then all you need is