Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Friday, November 11, 2011

Sorting SharePoint list item attachments

-This script is designed/tested only on Display form of list item.
-Add your attachment field under a div using SP designer, <div id="divAttachment"> <SharePoint:AttachmentsField ControlMode="Display" FieldName="Attachments" runat="server" Visible="true"/></div>
-Add below script on the page
<script language="javascript">
var fullHtml = $('#idAttachmentsTable').html();
var fileName = new Array();
var i = 0;
$("#idAttachmentsTable").find('a').each(function() {
fileName[i]  = new Array();
fileName[i][0]= $(this).text();
fileName[i][1] = $(this).attr('href');
i++;
});
fileName.sort();
document.getElementById('divAttachment').innerHTML = '';
for(var cntArr=0; cntArr<fileName.length;cntArr++)
{
 var strHref = "<a href='"+fileName[cntArr][1]+"'>"+fileName[cntArr][0]+"</a><br/>";
 document.getElementById('divAttachment').innerHTML += strHref;
}
</script>

Friday, March 25, 2011

Hide SharePoint List Fileds with blank value from Display form, using HTML comments

<script language="javascript" type="text/javascript">
_spBodyOnLoadFunctionNames.push("Fields");
function FindField(fieldName) {
   // get all the HTML comments
   var arr = document.getElementsByTagName("!");
  
   for (var i=0;i < arr.length; i++ )
   {
      // check the field name
      if (arr[i].innerHTML.indexOf(fieldName) != -1)
          return arr[i];     
        
   }
}
//implimenation of string trim function
String.prototype.trim = function() { return this.replace(/^\s+|\s+$/, ''); };
function Fields() {
   var field = FindField("All Day Event");
    HideField(field);
 field = FindField("Recurrence");
 HideField(field);
 field = FindField("Workspace");
 HideField(field);
}
function HideField(field)
{
 if( field!= null)
 {

 
  var childNods = field.parentNode.childNodes;
  for( var j=0; j< childNods.length;j++)
  {
   if(childNods[j].innerHTML != null)
    {
     var innerCode = field.parentNode.innerHTML;
     var cmtCode = childNods[j].innerHTML;
     var cmtEnd = innerCode.lastIndexOf("-->");
     var childCmtEnd = cmtCode.lastIndexOf("-->");
    
      if(childCmtEnd > 0)
      {
      
       var len=   innerCode.length;
       var fieldValue = innerCode.substring(cmtEnd + 3, len);
        if(fieldValue != null)
       {
        fieldValue = fieldValue.replace("&nbsp;","");
      
        fieldValue = fieldValue.trim();
         if(fieldValue == "" )
           field.parentNode.parentNode.style.display="none";
    
        }
      }
      else
      {
     if(childNods[j].outerHTML.indexOf("<IMG") != -1)
     continue;
    
     var otherThanCommentTag = childNods[j].innerHTML;
      otherThanCommentTag = otherThanCommentTag.replace("&nbsp;","");
      otherThanCommentTag = otherThanCommentTag.trim();
      otherThanCommentTag= otherThanCommentTag.replace(/<(.|\n)*?>/g,"");
 
      if(otherThanCommentTag == "" )
           field.parentNode.parentNode.style.display="none";
      
      }
 
   }
 }
 
}
}
</script>

Tuesday, April 28, 2009

Getting Current User and setting it to the People Picker using JavaScript

//Set People picker field to current user by Andy Bonner

_spBodyOnLoadFunctionNames.push("fillDefaultValues");



function fillDefaultValues()

{

fillPeoplePickerWithCurrentUser('Submitted_x0020_By');

}



function fillPeoplePickerWithCurrentUser(pickerName)

{

//get the current user from the welcome menu
var currentUser = getCurrentUser();
//check to see that we've got it
if(currentUser != null)
{
//get the people pickers input div
var pp = getPickerInputElement(pickerName);
//set it to the current user if we've found it
if(pp != null)
pp.innerHTML = currentUser;

}

}


function getCurrentUser()
{
var tags = document.getElementsByTagName('a');
for (var i=0; i < tags.length; i++)
{
if(tags[i].innerText.substr(0,7) == 'Welcome')
{
return tags[i].innerText.substr(8,tags[i].innerText.length);
}
}
}


function getPickerInputElement(fieldsInternalName)
{
var result = "";
var divs = document.getElementsByTagName("DIV");
for(var i=0; i < divs.length ; i++)
{
if(divs[i].id=="WebPartWPQ2")
{
var tds = divs[i].getElementsByTagName("TD");
for(var j=0; j < tds.length; j++)
{
var cellHTML = tds[j].innerHTML;
if(cellHTML.indexOf('FieldInternalName="' + fieldsInternalName + '"') >= 0)
{
var innerDivs = tds[j].getElementsByTagName("DIV");
for(var k=0; k < innerDivs .length; k++)
{
if(innerDivs[k].id.indexOf("UserField_upLevelDiv") > 0)
{
result = innerDivs[k];
break;
}
}
}
}
}
}
return result;
}

JavaScript funtion to hide fields on Newform.aspx/Editform.aspx

•TAGNAME: HTML element that is being rendered ("SELECT", "INPUT"...)

•IDENTIFIER: SharePoint field type identifier ("TextField", "DropDownChoice"...)

•FIELD NAME: Display name of the field (e.g. "Status", "Customer Name"...)



Script starts...


_spBodyOnLoadFunctionNames.push("hideFields");

function hideFields() {
var control = getTagFromIdentifierAndTitle("TAGNAME","IDENTIFIER","FIELD NAME");
control.parentNode.parentNode.parentNode.style.display="none";
}

function getTagFromIdentifierAndTitle(tagName, identifier, title) {
var len = identifier.length;
var tags = document.getElementsByTagName(tagName);
for (var i=0; i < tags.length; i++) {
var tempString = tags[i].id;
if (tags[i].title == title && (identifier == "" || tempString.indexOf(identifier) == tempString.length - len)) {
return tags[i];
}
}
return null;
}

Script ends...

you can also refer to this link

Monday, April 27, 2009

JavaScripts to Disable controls on Newform.aspx/Editform.aspx

JavaScripts to Disable controls on Editform.aspx


for(var i = 0; i < document.aspnetForm.elements.length; i++)
if ((document.aspnetForm.elements[i].title == "Recommendation")) // give the title of the control that you want to disable
{
document.aspnetForm.elements[i].disabled =
true;
}

JavaScript function to get element using tag name and title

function GetElementByText(tagName, title)
{
var a = document.getElementsByTagName(tagName);

for (var i=0; i < a.length; i++)
{
if (a[i].value)
{
if (a[i].value == title )
{
return a[i];
}
}
}
return null;
}

Add Custom Menu to List Item and Document Library Item

var siteUrl = GetSiteUrl();

function Custom_AddListMenuItems(m, ctx)
{
var copyCurrentItemId = currentItemID;
var titleText = null;

// Add Open Workspace menu item
var strDisplayText = "Request Home";
var strAction = "document.location.href='"+siteUrl+"/DCP/RequestPage.aspx?Request="+titleText+"&ID="+copyCurrentItemId+"'";
CAMOpt(m, strDisplayText, strAction);
CAMSep(m);


// false means that the standard menu items should also rendered

return false;
}

function me()
{
window.location = siteUrl + "/DCP/NewRequestByMgr.aspx?&Source="+GetSource();
}

function GetSiteUrl()
{
var siteUrl = window.location.href;
var copyOfSiteUrl = siteUrl;
siteUrl = siteUrl.split("/");
var isSubSite = false;
var url = null;

if(siteUrl[3] == 'sites')
{
isSubSite = true;

}
if(isSubSite)
{
copyOfSiteUrl = copyOfSiteUrl.split("sites/");
var subSiteName = copyOfSiteUrl[1].split("/");
url = copyOfSiteUrl[0] + "sites/" + subSiteName[0];
return url;
}
else
{
copyOfSiteUrl = copyOfSiteUrl.split("/");
url = copyOfSiteUrl[0] + "//" + copyOfSiteUrl[2];
return url;
}
}


For document library use
function AddDocLibMenuItems(m, ctx)
{
if (typeof(Custom_AddDocLibMenuItems) != “undefined”)
{
if (Custom_AddDocLibMenuItems(m, ctx))
return;
}
}
function instead of Custom_AddListMenuItems(m, ctx)
{
.....
}

Filtered Lookup Lists in SharePoint

SharePoint allows you to create custom lists with your own custom columns. One type you can use for these columns is a lookup against one of your other lists in the SharePoint site. By default this lookup gives the user all the items that are available in the list. Many times, you probably want to have a filtered list instead of the complete one.
Lately, I had to do exactly this for a customer. The approach explained here is probably not the only one you can take but it is one you can start with and it is not difficult to incorporate that within your NewForm/EditForm.aspx (the pages where you actually see the lookup). The approach I have taken is a small JavaScript function that repopulates the dropdown based on the items in the lookuplist that are visible via a view you create. Take for example a list that allows users to submit questions to SharePoint. Besides columns for capturing data regarding the question itself, the user also has to select the person who has to handle the question. In our case, the person submitting the question has one or more roles he or she can select from. A custom list storing this information is create to support the lookup that needs to be done.
When you create the Questions list, you can create a column Role that points to that second lookup list. Problem is that everything out of that list is displayed to the user and we want to have the user only see those entries that are relevant for him or her. So, I first thing I did was to create a new view on the second list that only displays all the roles for the logged on user. This view has the filter set to [Me] (a common practice when creating views).
Next thing you do is to open up the EditForm.aspx of the first list (the questions one) in FrontPage. At the bottom of the HTML (just before the closing BODY tag) you can add the following script blocks.


The first block points to a Javascript file with a generic function to repopulate lists (note that it needs more exception handling to become really generic!). Here is the content of that file:

function RepopulateList(controlName,siteName,lookupListName,lookupViewName,textField,valueField) { // -- retrieve the list for the elements var listEl = document.getElementsByName(controlName) // -- emptying the listif(listEl.length>0) { listEl(0).innerHTML = ""; // -- getting the filtered lookup var reqstring = siteName + "/_vti_bin/owssvr.dll?CS=109&XMLDATA=1&RowLimit=0&List=" + lookupListName + "&View=" + lookupViewName; var req = new ActiveXObject("MSXML2.XMLHTTP"); req.open("GET",reqstring,false); req.send(); // -- loading response in XML Document var doc = new ActiveXObject("MSXML2.DOMDocument"); doc.loadXML(req.responseText); var data = doc.documentElement.childNodes(1); for (i=0;i

The second script block calls this function providing it the necessary values to go back to the server and retrieve the XML with only the data provided by the created view. I use that XML to repopulate the list then. Notice the owssvr.dll I am calling in the script. When you look at a view in a SharePoint, you can always view the source of that page and at the bottom of the page you will find the following information: You can copy this link and run it in the browser. The result is the following: This is the response I need to repopulate the dropdown then with only the roles for the current visitor. The performance is not that great if you apply this technique for big lookup lists so be careful. Test it first for your own specific scenario. To filter big lookup lists, you better have a look at your own custom ASP.NET control.

You can refer to this link as well

JavaScript Funtions to get Query String Value, Host Name and Site Url

function GetQueryString( name )
{
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
{
if(results[1].indexOf('+')!= '-1')
{
results = results[1].replace('+',' ');
return results;
}
if(results[1].indexOf('%')!= '-1')
{
results = results[1].replace('%20',' ');
return results;
}
else
return results[1];

}
}


function getHost()
{
var url = window.location;
var urlparts = url.split('/');
var host = urlparts[0];
return host;
}

function GetSiteUrl()
{
var siteUrl = window.location.href;
var copyOfSiteUrl = siteUrl;
siteUrl = siteUrl.split("/");
var isSubSite = false;
var url = null;

if(siteUrl[3] == 'sites')
{
isSubSite = true;

}
if(isSubSite)
{
copyOfSiteUrl = copyOfSiteUrl.split("sites/");
var subSiteName = copyOfSiteUrl[1].split("/");
url = copyOfSiteUrl[0] + "sites/" + subSiteName[0];
return url;
}
else
{
copyOfSiteUrl = copyOfSiteUrl.split("/");
url = copyOfSiteUrl[0] + "//" + copyOfSiteUrl[2];
return url;
}
}