Set datefield to first day of month, today’s date or last day of month

Change log
April 9, 2014
Updated the code example to fix some quotes that was formatted wrong due to migrating from my old server a long time ago. I also updated the function init_fields in the example.

I got this request from Charlie:

Hi Alexander:
Is it possible to add a clickable “button” or icon next to a date picker that would insert “Today’s Date” into the field box?

Yes it is. Here’s a solution for setting either “first day of month”, “today” or “last day of month” by clicking on a link above the date picker, or by pressing “F”, “T” or “L” in the date picker field itself.

IMG

As always we start like this:
Create a document library to hold your scripts (or a folder on the root created in SharePoint Designer). In this example i have made a document library with a relative URL of “/test/English/Javascript” (a sub site named “test” with a sub site named “English” with a document library named “Javascript”):
IMG

The jQuery-library is found here. The pictures and the sourcecode refers to jquery-1.3.2.min. If you download another version, be sure to update the script reference in the sourcecode.

The code for the file “DateFieldValueOnClick.js” is found below.

Add a CEWP belowit is essential that it is placed below – your list-form as briefly described here, and add this code:

<script type="text/javascript" src="/Javascript/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="/Javascript/DateFieldValueOnClick.js"></script>
<script type="text/javascript">
	// Array of fields to add this function to
	var arrOfFields = ['MyDateColumn1','MyDateColumn2'];
	setDateFieldValue(arrOfFields);
</script>

The variable “arrOfFields” is an array of the FieldInternalNames of all the date picker-fields you want to add this feature to.

The code for the file “DateFieldValueOnClick.js” looks like this:

/* Set datepicker value to "first day of month", "today" or "last day if month"
 * ---------------------------------------------
 * Created by Alexander Bautz
 * alexander.bautz@gmail.com
 * https://spjsblog.com
 * v1.1
 * LastMod: 09.04.2014 
*/

function setDateFieldValue(arrOfFieldInternalNames){
if(typeof fields === 'undefined')fields = init_fields_v2();
// Get today's date
var today = new Date();
var m = today.getMonth()+1;
var d = today.getDate();
var y = today.getFullYear();
// Find last day in month
var lastDayRaw = new Date(y,m,0);
var dLast = lastDayRaw.getDate();

// Format your date
var T = m + "/" + d + "/" + y; // Today
var F = m + "/" + 1 + "/" + y; // First day in month
var L = m + "/" + dLast + "/" + y; // Last day in month
var fieldMouseoverTitle = "Press \"F\" for " + F + ", \"T\" for " + T + ", \"L\" for " + L;
$.each(arrOfFields,function(idx,item){
if(fields[item]==undefined)return;
$(fields[item]).find('input').attr('title',fieldMouseoverTitle).keyup(function(e){
if(e.keyCode==70){
setDate(item,F);
}
if(e.keyCode==84){
setDate(item,T);
}
if(e.keyCode==76){
setDate(item,L);
}
}).parents('td.ms-formbody:first').prepend("<div><span title='Set field value to \"" + F + "\"' style='cursor:pointer;' onclick=setDate(\"" + item + "\",\"" + F +"\")>First</span> | <span title='Set field value to \"" + T + "\"' style='cursor:pointer;' onclick=setDate(\"" + item + "\",\"" + T + "\")>Today</span> | <span title='Set field value to \"" + L + "\"' style='cursor:pointer;' onclick='setDate(\"" + item + "\",\"" + L +"\")'>Last</span></div>");
});
}

function setDate(fieldName,date){
	$(fields[fieldName]).find('input').val(date);
}

function init_fields_v2(){
	var res = {};
	$("td.ms-formbody").each(function(){
	var myMatch = $(this).html().match(/FieldName="(.+)"\s+FieldInternalName="(.+)"\s+FieldType="(.+)"\s+/);	
		if(myMatch!=null){
			// Display name
			var disp = myMatch[1];
			// FieldInternalName
			var fin = myMatch[2];
			// FieldType
			var type = myMatch[3];
			if(type=='SPFieldNote'){
				if($(this).find('script').length>0){
					type=type+"_HTML";
				}else if($(this).find("div[id$='TextField_inplacerte']").length>0){
					type=type+"_EHTML";
				}				
			}
			if(type==="SPFieldLookup"){
				if($(this).find("input").length>0){
					type=type+"_Input";
				}
			}
			// HTML Calc
			if(type==='SPFieldCalculated' && $(this).text().match(/(<([^>]+)>)/ig)!==null){
				$(this).html($(this).text());
			}		
			// Build object
			res[fin] = this.parentNode;
			$(res[fin]).attr('FieldDispName',disp);
			$(res[fin]).attr('FieldType',type);
		}		
	});
	return res;
}

Save this code as “DateFieldValueOnClick.js”, and upload to the script library as shown above.

Ask if something is unclear.

Regards
Alexander

15 thoughts on “Set datefield to first day of month, today’s date or last day of month”

  1. Once again, you are the King! This is great stuff.

    What lines do I comment out to only get “Today”… and where do I do that? Perhaps in a copy of the “JS” file?

    Charlie Epes

  2. Sorry. I found where to comment out the First and Last, leaving only the today. I just copied the “js” file and renamed it.

    Thanks-

    Charlie Epes

  3. Hi Alexander:
    Is it possible to make a link that would add 5, 7, or 10 days to today’s date?

    Example: I want to enter a date in [Follow-Up Date] that is 5 days from today’s date.

    Even better would be the ability to add a specific number of “business days” to today’s date. Business days = Monday through Friday.

    Thanks & I hope you are well.
    Charlie

    1. Hi Alex:
      I know you answered the request for the 12, 18 month but I was wondering if it’s possible to make a link that would add 5, 7, or 10 days to today’s date?

      Thanks-

  4. Hi Alexander:
    I had a request from a user to change the “First, Today, Last” date selection to be “12 mos, 18 mos, 36 mos”
    (for 12 months from today, 18 months from today, or 36 months from today).

    Is this possible?

    Thanks as always-

    Charlie Epes

    1. Here is some help on the way:
      Add this below line 35 to add 18 month:

      var plus18 = new Date(y,m+18,d);
      var plus18m = (plus18.getMonth()+1) + "/" + plus18.getDate() + "/" + plus18.getFullYear(); // Today + 18 month
      

      Add this line to the string build in line 49-53:

      "<a title="Set fields's value to " + plus18m + "" href="javascript:setDate('" + item + "','" + plus18m +"')">Plus 18 month</a>" +
      "</div>");
      

      Alexander

    1. I’m not sure if this question is posted in the right category, but the problems with rich text fields regarding tabs and accordions is not resolved. I cannot promise any solutions to that issue.

      Alexander

  5. Hi Alexander:
    I have been using your “Set datefield to first day of month…” solution https://sharepointjavascript.wordpress.com/2009/12/03/set-datefield-to-first-day-of-month-todays-date-or-last-day-of-month/ more and more lately.

    I have several date fields in a SP List that signify stages in a linear process. Sometimes, the date field is meaningless and the user needs to leave it blank.

    Can you think of other ways to signify that the date field is not needed? Here are some ideas:

    Instead of “First, Today, Last” options, add a “N/A” option (not applicable) which would
    • enter a fixed date of “1/1/2199
    • add a gray color to the field showing that it is obsolete

    Thoughts?

  6. Hi Alexander:
    I figured it out. I just commented out “First” and then changed the code for “Last” to read “Not Applicable” and used a fixed date of “12/31/8900”.

    Charlie Epes

  7. Hi Alex:
    I’m dregding an older classic of yours. I cannot seem to get this to work in SP2010. Can you advise me about how to adapt it?
    Thanks-
    Charlie Epes

    1. Hi,
      Thank you for the donation.
      I did a quick test of the solution in SharePoint Foundation 2010 and it works as expected. Are you sure the scripts are referred correctly?

      Alexander

  8. Hi Alex:
    Still using this solution!!

    I can’t seem to get this working with JQuery 1.7.1 min. Any idea why>

    Thanks-

    Charlie

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.