views:

764

answers:

3

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?

A: 

Looks like it's just faulty logic here:

var d = new Date();

d.getDate( element.value ); // HERE: what is this suppose to do?

d.setDate( d.getDate() + 1 );
element.value = ( d.getMonth() + 1 ) + "/" + d.getDate() + "/" + d.getYear();

You are basically setting element.value to tomorrow everytime.

Roatin Marth
A: 

You need to change

var d = new Date();

to

var d = new Date(element.value);

and get rid of

d.getDate( element.value );

You also need to move your return false; to after the element.select() line.

JustLoren
Thanks. That did the trick.
Michael Itzoe
A: 

The getDate() method in your example does not take a parameter. It returns the day of the month. So try assigning the 'current' date value in the constructor.

Give this a try:

if( isDate( element.value ) ) {
  var d = new Date( element.value );
  d.setDate( d.getDate() + 1 );
  element.value = d.toDateString();
} else {
  element.value = new Date().toDateString();
}

Also give the w3c page a peek, it contains useful methods you could consider.

Yannick M.