Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Help with this date format problem 1

Status
Not open for further replies.

linuxjr

Programmer
Jun 2, 2001
135
0
0
US
I have a simple formatDate function written in javascript as seen below.

Code:
	<script language="javascript">
			function formatDate(str, style) {
				var dateVar = new Date(str);
				var year = dateVar.getYear();
				if(year<10)
					year += 2000;
				if(year<100)
					year += 1900;
				switch(style) {
					case "MM/DD/YY":
						return ((dateVar.getMonth() + 1) + "/" + dateVar.getDate() + "/" + year);
						break;
}
			}

I'm trying to add an onchange property to my textbox so it will format the date after the user types in a value so I have added this line to my codebehind file as follow:
Code:
calfield1.Attributes.Add("onchange","formatDate(this.value, 'MM/DD/YY')");

When I step through the javascript it returns the correct format but it does not update my textbox at all.

Any tips or suggestions be greatly appreciated.
 
A few suggestions:
Code:
[B][I]Use the getFullYear method instead of getYear[/I][/B]

function formatDate(str, style) {
   var dateVar = new Date(str);
   var year = dateVar.get[!]Full[/!]Year();
[s]   if(year<10)
      year += 2000;
   if(year<100)
      year += 1900;[/s]
   switch(style) {
      case "MM/DD/YY":
         return ((dateVar.getMonth() + 1) + "/" + dateVar.getDate() + "/" + year);
         break;
   }
}

Additionally, the reason that the input box is not getting updated is because you are not explicitly setting the value of the textbox. The function returns the value, but then you're not doing anything with it. So, try this:
Code:
calfield1.Attributes.Add("onchange","[!]this.value = [/!]formatDate(this.value, 'MM/DD/YY')");

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Did this fix your problem?

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
kaht,
Thanks for the follow up. I was sent out into the field and just got back to work on this little problem. Thanks for the tip about the getFullYear() and after a few adjustments. I finally got it working. Thanks again for your help.
 
[thumbsup2]

-kaht

How much you wanna make a bet I can throw a football over them mountains?
sheepico.jpg
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top