Geeks With Blogs
Thorvald Bøe
I love the SharePoint lists, they are so easy to set up and customize. I use it all the time.

Still, there is room for improvement. The display/new/edit forms for example, are not very customizable OOTB. However, by making some very simple tweaks, you can make great improvements. This time I had a form displaying a couple of date fields, where it was desired to display default values based on some simple logic.

The basic problems here are:
1.SharePoint has very limited functionality for default values OOTB
2.Date handling in javascript is a bi#%& (spoiler alert..)

I will not go in detail on my specific solution, but instead show a generic pattern that can be used in a wide range of scenarios, to solve these problems. This was done in SharePoint Online, but it also works in OnPremise.


1.First, add a content editor web part to the edit form by clicking the link at the top of the form (sorry for the Norwegian)

2.Set up the cewp to point to a html file that you add in site assets using sharepoint designer. Also set the chrome type to none, so that it won't be visible on the page - the page is just a place holder for your custom jQuery code

3.Start editing the html file in SharePoint designer. Insert a head tag for jquery and moment.js

<head>
<script type="text/javascript" src="//code.jquery.com/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>
</head>

4.Locate the control that you want to work with

var myDate = $("input[id^='Delivery_x0020_date']")[0]; //starts with "delivery date"
var myDateStr = $(myDate).val();


5.Set the desired value, e.g. by adding some days
var myDateVal = moment().add(7, "days"); //add 1 week from now
//OR
var tempDate = moment(myDateStr, "DD.MM.YYYY"); //parse date using given format
myDateVal = moment(tempDate).add(7, "days"); //add 1 week from the already entered date

//format the date
var myDateStr = moment(myDateVal).format("DD.MM.YYYY");

//set the date control
var deliveryDateControl = $("input[id^='Delivery_x0020_date']")[0];
$(deliveryDateControl).val(myDateStr); //set the new date


Two lessons learned:
1.You can do great things by injecting javascript in your SharePoint forms
2.Moment.js rocks when dealing with dates in javascript. The built in functions have loads of problems, moment.js solves them in a simple, intuitive way, and it works!




Posted on Friday, March 6, 2015 9:51 AM jquery , sharepoint , momentjs | Back to top


Comments on this post: Add default values for date fields in list edit forms using moment.js

No comments posted yet.
Your comment:
 (will show your gravatar)


Copyright © Thorvald Bøe | Powered by: GeeksWithBlogs.net