Comparing Dates in SharePoint


SCENARIO:

Let us assume that we need to hide some fields in SharePoint form based on other field value such as text box, what will we do? We will just check the value of the field on page load in edit form as shown below:

<script src="../Scripts/jquery.min.js"></script>
<script type="text/javascript"> 
$(document).ready(function()
{
if($("input[title='Title']").val()=="Text1") 
{
//hide fields
} 
});
</script>

This is pretty much simple. But assume that we need to hide some fields based on date and time value where Date and Time field is split into three controls:

  • Text box for Date along with Date Picker
  • Dropdown box to select Hours
  • Dropdown box to select Minutes

On seeing the three controls, we may think it is very complicated. Certainly not. We are going to achieve this by retrieving the id of date textbox and then append the id with the words, “Hours” and “Minutes” to get the value of Hours and Minutes dropdown. So, this will be quite interesting. Let’s start.

Retrieving value from Date and Time field:

The below code shows how to retrieve value from date and time field in edit form on page load. If we need to check the value of date and time field in new form on save button for some other requirement, use PreSaveAction function instead of document.ready function

<script src="../Scripts/jquery.min.js"></script>
<script type="text/javascript"> 
$(document).ready(function()
 {
 var startDate=getDateField("Start Date");//Display name of Date and Time field
 alert(startDate);
 });
 function getDateField(field)
 {
 var date = $(":input[title='" +field+ "']").val(); //retrieves date from date text box which is in mm/dd/yyyy format
 var d = new Date(date);
 var month =d.getMonth() + 1; //adding 1 as January starts at 0
 var day =d.getDate();
 var year = d.getFullYear();
//appending 0 for single digit date ad month
 if (month.length < 2) month = '0' + month; 
if (day.length < 2) day = '0' + day;
var dateID = $(":input[title='"+field+"']").attr("id");
var dateHours = $(":input[id='"+ dateID + "Hours" +"']").val();
var Meri=dateHours.split(' ')[1];
dateHours = dateHours.split(' ')[0];
//converting it into 24 hour format
 if(Meri == "PM" && dateHours<12)
    dateHours = parseInt(dateHours)+12;
 else if(Meri == "AM" && dateHours==12)
   dateHours = parseInt(dateHours)-12;
var dateMinutes=$(":input[id='"+dateID+"Minutes"+"']").val();
 var requiredDate=new Date(year,month-1,day,dateHours,dateMinutes,0);
 return requiredDate;
 }
</script>

To retrieve date and time in display form, use the below code:

<script src="../Scripts/jquery.min.js"></script>
<script type="text/javascript"> 
$(document).ready(function()
 {
var start = $.trim($('h3:contains("Start Date")').closest('td').next('td').text());
alert(start);
});
</script>

Comparing Current Date and time with Date in DateTime field:

After retrieving the value from Date and Time field, let’s say we need to check the current date and time and hide if current date is greater than Start Date field.

<script src="../Scripts/jquery.min.js"></script>
<script type="text/javascript"> 
$(document).ready(function()
 {
 var startDate=getDateField("Start Date");//Display name of Date and Time field
 var current=new Date();
 if(current>=startDate)
 {
 //hide fields
 }
 });
 function getDateField(field)
 {
var date = $(":input[title='" +field+ "']").val(); //retrieves date from date text box which is in mm/dd/yyyy format
var d = new Date(date);
var month =d.getMonth() + 1; //adding 1 as January starts at 0
var day =d.getDate();
var year = d.getFullYear();
//appending 0 for single digit date ad month
 if (month.length < 2) month = '0' + month; 
if (day.length < 2) day = '0' + day;
var dateID = $(":input[title='"+field+"']").attr("id");
var dateHours = $(":input[id='"+ dateID + "Hours" +"']").val();
var Meri=dateHours.split(' ')[1];
dateHours = dateHours.split(' ')[0];
//converting it into 24 hour format
 if(Meri == "PM" && dateHours<12)
    dateHours = parseInt(dateHours)+12;
 else if(Meri == "AM" && dateHours==12)
   dateHours = parseInt(dateHours)-12;
var dateMinutes=$(":input[id='"+dateID+"Minutes"+"']").val();
var requiredDate=new Date(year,month-1,day,dateHours,dateMinutes,0);
 return requiredDate;
 }
</script>

To compare two SharePoint date fields, we need to call getDateField function for both the dates as:

<script src="../Scripts/jquery.min.js"></script>
<script type="text/javascript"> 
$(document).ready(function()
 {
var startDate=getDateField("Start Date");//Display name of Date and Time field
var EndDate=getDateField("End Date");
 if(EndDate<=startDate)
 {
 alert("End Date should be greater than Start Date)
 }
 });
</script>

Hiding fields before three hours of start date in SharePoint

To hide the fields from three hours prior to start Date  time, lets subtract three hours from Start Date time and then compare with current date and time as shown below:

<script src="../Scripts/jquery.min.js"></script>
<script type="text/javascript"> 
$(document).ready(function()
 {
 var startDate=getDateField("Start Date");//Display name of Date and Time field
 var current=new Date();
 var subbed = new Date(startDate - 3*60*60*1000); // subtract 3 hours
 if(current>=subbed)
 {
 //hide fields
 }
});
function getDateField(field)
 {
var date = $(":input[title='" +field+ "']").val(); //retrieves date from date text box which is in mm/dd/yyyy format
var d = new Date(date);
var month =d.getMonth() + 1; //adding 1 as January starts at 0
var day =d.getDate();
var year = d.getFullYear();
//appending 0 for single digit date ad month
 if (month.length < 2) month = '0' + month; 
if (day.length < 2) day = '0' + day;
var dateID = $(":input[title='"+field+"']").attr("id");
var dateHours = $(":input[id='"+ dateID + "Hours" +"']").val();
var Meri=dateHours.split(' ')[1];
dateHours = dateHours.split(' ')[0];
//converting it into 24 hour format
 if(Meri == "PM" && dateHours<12)
    dateHours = parseInt(dateHours)+12;
 else if(Meri == "AM" && dateHours==12)
   dateHours = parseInt(dateHours)-12;
var dateMinutes=$(":input[id='"+dateID+"Minutes"+"']").val();
var requiredDate=new Date(year,month-1,day,dateHours,dateMinutes,0);
 return requiredDate;
 }
</script>

Please do not forget to like or rate the article 😛

 

 

PART 2 : Working in MOSS using SPServices


In this article, we will see how to set and get People Picker value using SPFindPeoplePicker.

Get value from the people Picker:


<script>

var ppl = $().SPServices.SPFindPeoplePicker({
peoplePickerDisplayName: "User", //Display Name of People Picker Field
checkNames: true
});
alert(ppl.currentValue);

</script>

Set value to the People Picker:

To set static value in  the People Picker:


<script>

$(document).ready(function()
{
$().SPServices.SPFindPeoplePicker({
peoplePickerDisplayName: "User",
valueToSet: "kamal",
checkNames: true
});
});

</script>

To set logged in user name to the People Picker:


<script>

$(document).ready(function()
{
var user= $().SPServices.SPGetCurrentUser();
$().SPServices.SPFindPeoplePicker({
peoplePickerDisplayName: "User",
valueToSet: user,
checkNames: true
});
});

</script>

PART 1 : Working in MOSS using SPServices


After working in SharePoint 2010 and 2013 platform, it was bit difficult for us to work in SharePoint 2007.  SPServices came to our rescue. I have consolidated different scenarios we encountered and placed them in a single post below. So, it might help someone in the future.

Download the below files, save and provide a reference to these scripts before using the below script:

SPServices to populate people picker with logged-in username and to disable it in IE and Chrome:

<script type="text/javascript"> 
    var currentUserName ;   
    $(document).ready(function() {
    currentUserName = $().SPServices.SPGetCurrentUser({
    fieldName: "Title",
    debug: false
});
 alert(currentUserName);
 if((navigator.userAgent.indexOf("MSIE") != -1 ) || (!!document.documentMode == true )) //IF IE > 10
      {
          alert("Browser used for display is IE");          
      $("div[title='People Picker']").text(currentUserName);
      $("div[title='People Picker']").prop('disabled',true);
       $('img[title="Browse"]').css('display','none');
       $('img[title="Check Names"]').css('display','none');
        
      }     
      else if(navigator.userAgent.indexOf("Chrome") != -1 )
      {
          alert("Browser used for display is Chrome");  
   $("textarea[title='People Picker']").val(currentUserName);
      $("textarea[title='People Picker']").prop('disabled',true);
      $('img[title="Browse"]').css('display','none');
      $('img[title="Check Names"]').css('display','none');    
        
      }
 });
</script>

SPServices to check whether the user belongs to the specific SharePoint group(say, Admin):

<script language="javascript" type="text/javascript">
$(document).ready(function() 
{
    $().SPServices({
      operation: "GetGroupCollectionFromUser",
      userLoginName: $().SPServices.SPGetCurrentUser(),
      async: false,
      completefunc: function(xData, Status) {
        if($(xData.responseXML).find("Group[Name='Admin']").length == 1)
        {
      alert("You belong to admin group");
  //your code for admin users
    }
        else
        {
          alert("You do not belong to admin group");
  //your code for non-admin users
        }
      }
   }); 
}); 
</script>

SPServices to perform read operation:

<script>
$(function(){
getListItems();
});
function getListItems(){
var method = "GetListItems";
var list = "Demo";
var fieldsToRead =  '<ViewFields></ViewFields>';
var query = "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Number'>"+ID+"</Value></Eq></Where></Query>";            $().SPServices({
operation: method,
async: false,
listName: list,
CAMLViewFields: fieldsToRead,
CAMLQuery: query,
completefunc: function (xData, status) {
$(xData.responseXML).SPFilterNode("z:row").each(function () {
var eTitle = ($(this).attr("ows_Title"));
alert(eTitle);
});
}
});
}
</script>

To get the latest version of SPServices and to know more about it, visit this link

Query Strings in SharePoint


Let us see some of the query strings used in SharePoint:

  • contents=1 ->used to troubleshoot the sharepoint page.When it is appended at the end of the url as:

https://…/sitepages/Home.aspx?contents=1

it takes us to webpart maintenance page where we can find the webpart causing the error by trying to close each one and deleting the problematic webpart

  • IsDlg=1->used to hide the header and quick launch(i.e. chrome).Generally used in SharePoint forms.
  • FilterField1=Gender&FilterValue1=Male(FilterField1=columnname&FilterValue1=columnvalue)->used to filter sharepoint list webpart with the condition, Gender=”Male”
  • FilterName=Hobbies&FilterMultiValue=Painting;Reading(FilterName=columnname&FilterMultiValue=columnvalue1; columnvalue2)->used to filter sharepoint list with multiplevalues in singlecolumn
  • PageView=Shared&ToolPaneView=2->used to show the edit mode of the page, browse and add the webpart
  • PageView=Shared&ToolPaneView=3->used to show the edit mode of the page, search and add the webpart
  • SortField=Hobbies&SortDir=Desc(SortField=ColumnName&SortDir=Desc/Asc) ->used to sort the sharepoint list by Hobbies in Descending order
  • _layouts/viewlsts.aspx -> To go to “All Site Content” Page