Adding / Subtracting Days to Date in HTML Form

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

Adding / Subtracting Days to Date in HTML Form

Post by millsy007 »

I have a html textbox (txtdate) in which a date is entered using a javascript calendar, in the format 01/30/2009
I have added two href links either side of the calendar one 'next day' the other 'previous day'. Obviously when these are clicked I want the calendar date that is currently in the textbox to move on/back one day.
Is this something that could be achieved fairly easily using some javacript or should i use php?
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: Adding / Subtracting Days to Date in HTML Form

Post by sparrrow »

Quick search on google brings up lots of info on managing dates in Javascript. http://social.msdn.microsoft.com/Forums ... ca3f6634a/ was the simplest I saw. Also look at http://www.quackit.com/javascript/javas ... ctions.cfm

Try this:

Code: Select all

<script language="javascript">
function shiftDate(days, up_or_down)
{
  date = new Date(document.getElementById('datefield').value);
 
  if (up_or_down == 'up') {
    date.setDate(date.getDate() + days);
  } else {
    date.setDate(date.getDate() - days);
  }
  
  document.getElementById('datefield').value = (date.getMonth()+1)+"/"+date.getDate()+"/"+date.getFullYear();
  return false;
}
</script>
And for the HTML:

Code: Select all

<a href="#" onclick="shiftDate(1, 'down');">Previous</a>
<input name="datefield" id="datefield" />
<a href="#" onclick="shiftDate(1, 'up');">Next</a>
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

Re: Adding / Subtracting Days to Date in HTML Form

Post by millsy007 »

Thanks for the advice unfortunately that example didnt work, there were no errors but the date in the textbox didnt change.

My text field is actually called 'date' can this cause conflicts?

Also is my date in the correct format, it shows in the textbox as 01/30/2009 how can I see if this is what the javascript expects?
sparrrow
Forum Commoner
Posts: 81
Joined: Mon Oct 20, 2008 12:22 pm

Re: Adding / Subtracting Days to Date in HTML Form

Post by sparrrow »

Firstly, make sure you have your text box id defined. Second, in my code, substitute anywhere you see datefield with "date" or whatever your textbox ID is.

Code: Select all

<input name="date" id="date" />
millsy007
Forum Commoner
Posts: 78
Joined: Wed Jul 02, 2008 7:00 pm

Re: Adding / Subtracting Days to Date in HTML Form

Post by millsy007 »

Sorry yeah i was missing that, works now. Thanks :D
Post Reply