Targa wrote:
I have a form field which displays a time in the format 5:30 PM - this time
is selected from a previous page.
I need to add a function to increment or deincrement the time by clicking
up/down buttons - sort of like the clock in Windows.
How can this be done in javascript?
Thanks in advance!
Here's a quick stab at it:
<head>
<script type="text/javascript">
function getClockTime() {
//get current time
var now = new Date();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var ap = "AM";
if (hour > 11) { ap = "PM"; }
if (hour > 12) { hour = hour - 12; }
if (hour == 0) { hour = 12; }
if (hour < 10) { hour = "0" + hour; }
if (minute < 10) { minute = "0" + minute; }
if (second < 10) { second = "0" + second; }
//var timeString = hour + ':' + minute + ':' + second + " " + ap;
var timeString = hour + ':' + minute + " " + ap;
document.getElementById("time").innerText=timeStri ng;
}
function changetime(interval,direction) {
//chamge hours or minutes up or down
var currentdisplay =
document.getElementById('time').innerText.toUpperC ase();
var times=currentdisplay.split(':');
var h_current = parseFloat(times[0]); //hours
var m_current = parseFloat(times[1]); //minutes
var len = currentdisplay.length;
var ap = currentdisplay.substring(len-2,len); //AM or PM
var h_new=h_current;
var m_new=m_current;
if (interval=='h') {
if (direction=='+') h_new += 1;
if (direction=='-') h_new -= 1;
}
if (interval=='m') {
if (direction=='+') m_new += 1;
if (direction=='-') m_new -= 1;
}
if (m_new > 59) {
h_new += 1;
m_new -= 60;
}
if (m_new < 0) {
m_new = 59;
h_new -= 1;
}
if (h_new == 0) {
h_new=12;
ap=flipampm(ap);
}
if (h_new > 12) {
h_new -= 12;
ap=flipampm(ap);
}
if (h_new < 10)
h_new= '0' + h_new;
if (m_new < 10)
m_new = '0'+m_new;
var timeString = h_new + ':' + m_new + " " + ap;
document.getElementById("time").innerText=timeStri ng;
return true;
}
function flipampm(ap) {
//swap am-pm
if (ap == 'AM')
ap='PM';
else
ap='AM';
return ap;
}
</script>
<title>change time</title>
</head>
<body onload="getClockTime()">
Adjust the Time<p>
<div name="time" id="time"></div>
<p> </p>
<p>
Hours
<input type="button" value=" - " onclick="changetime('h','-')">
<input type="button" value=" + " onclick="changetime('h','+')">
<br>
Minutes
<input type="button" value=" - " onclick="changetime('m','-')">
<input type="button" value=" + " onclick="changetime('m','+')">
</body>