I have a standard <input>
textbox where users enter a date. I'd like to add some functionality where users can enter +
or -
to add/subtract a day from the value. I added an onkeypress
event that calls this function:
function adjustDate( element ) {
var e = event || window.event;
var code = e.charCode || e.keyCode;
switch( code ) {
case 43: // user pressed "+" (plus)
if( isDate( element.value ) ) {
var d = new Date();
d.getDate( element.value );
d.setDate( d.getDate() + 1 );
element.value = ( d.getMonth() + 1 ) + "/" + d.getDate() + "/" + d.getYear();
} else {
var today = new Date();
element.value = ( today.getMonth() + 1 ) + "/" + today.getDate() + "/" + today.getYear();
}
if( e.preventDefault ) e.preventDefault();
else e.returnValue = false;
return false;
element.select();
break;
case 45: // user pressed "-" (minus)
// ...
}
}
The isDate
function I pulled off Google and works, but I can post it too if necessary.
My problem is the works one time, then nada. For instance, if the textbox's value is 10/1/2009
then pressing +
will make it 10/2/2009
, but no effect on subsequent plusses. Then, if I press -
it goes to 9/30/2009
instead of back to 10/1/2009
, and ignores subsequent minus keypresses.
I'm testing on IE8. This is an internal web app so other browsers would be nice but not necessarily required. I'm not currently using jQuery or any other framework, and for what this is would probably be overkill, so I'm looking for a pure Javascript solution. In fact, this feature is merely a "nice to have" and not something I need to spend much more time on.
I know I'm either missing something or doing it entirely wrong. So which is it?