SharePoint 2010 Javascript Examples

This SharePoint tutorial, we will discuss a very few JavaScript object model examples in SharePoint 2010.

Update SharePoint List item using jsom (javascript object model):

First, we will see how to update SharePoint list items using javascript which makes an ajax call to SharePoint Web Services.

<script type="text/javascript">
function update()
{
var UpdateNewItemXml= "<Batch OnError=’Continue’ ListVersion=’1′>"
+ "<Method ID=\"1\" Cmd=\"Update\">"
+ "<Field Name=’ID’>2</Field>"
+ "<Field Name=’Name’>Mack</Field>"
+ "</Method>"
+ "</Batch>";
FeedbackHTTP = new ActiveXObject("MSXML2.XMLHTTP.3.0");
FeedbackHTTP.Open("POST", "http://spsrvr:800/sites/test/_vti_bin/lists.asmx", false);
FeedbackHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
FeedbackHTTP.setRequestHeader("SOAPAction","http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
var strSOAP = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<soap:Envelopexmlns:xsi=\"http://www.w3.org/2001/XMLSchemainstance\"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body>"
+ "<UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
+ "<listName>MyList</listName>"
+ "<updates>"+ UpdateNewItemXml + "</updates>"
+ "</UpdateListItems>"
+ "</soap:Body>"
+ "</soap:Envelope>";
FeedbackHTTP.Send(strSOAP);
alert("Thank you! your suggestion has been Updated successfully.");
}
</script>

This is how we can update sharepoint 2010 list items by doing the web service call using JavaScript.

Delete SharePoint List item using jsom (javascript object model)

Now, we will see how to delete SharePoint list items using JavaScript object model (jsom) by making an ajax call to SharePoint Web Services.

<script type="text/javascript">
function Delete ()
{
var UpdateNewItemXml= "<Batch OnError=’Continue’ ListVersion=’1′>"
+ "<Method ID=\"1\" Cmd=\"Delete\">"
+ "<Field Name=’ID’>2</Field>"
+ "<Field Name=’Name’>Mack</Field>"
+ "</Method>"
+ "</Batch>";
FeedbackHTTP = new ActiveXObject("MSXML2.XMLHTTP.3.0");
FeedbackHTTP.Open("POST", "http://sp2k10srvr:800/sites/test/_vti_bin/lists.asmx", false);
FeedbackHTTP.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
FeedbackHTTP.setRequestHeader("SOAPAction","http://schemas.microsoft.com/sharepoint/soap/UpdateListItems");
var strSOAP = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
+"<soap:Envelopexmlns:xsi=\"http://www.w3.org/2001/XMLSchemainstance\"xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">"
+ "<soap:Body>"
+ "<UpdateListItems xmlns=\"http://schemas.microsoft.com/sharepoint/soap/\">"
+ "<listName>31stmay</listName>"
+ "<updates>"+ UpdateNewItemXml + "</updates>"
+ "</UpdateListItems>"
+ "</soap:Body>"
+ "</soap:Envelope>";
FeedbackHTTP.Send(strSOAP);
alert("Thank you! your suggestion has been Deleted successfully.");
}

This is how we can delete items in SharePoint 2010 by doing the web service call using JavaScript.

Dropdown list with multiple selection option in SharePoint 2010

Now, we will see how to make a dropdown list with multiple selection option in SharePoint 2010 in jQuery.

The dropdown with multiple selection will look like below:

Dropdown list with multiple selection option in SharePoint

Below is the css code:

<style type="text/css">
.DivClose
{
display: none;
position: absolute;
width: 150px;
height: 220px;
border-style: solid;
border-color: Gray;
border-width: 1px;
background-color: #F0FFFF;
}

.LabelClose
{
vertical-align: text-top;
position: absolute;
bottom: 0px;
font-family: Verdana;
}
.DivCheckBoxList
{
display: none;
background-color: White;
width: 150px;
position: absolute;
height: 200px;
overflow-y: auto;
overflow-x: hidden;
border-style: solid;
border-color: Gray;
border-width: 1px;
width: 150px;
}

.CheckBoxList
{
position: relative;
width: 150px;
height: 10px;
overflow: scroll;
font-size: small;
}
.Maintitle
{
text-align: left;
margin: 0em;
color: #00008B;
font-size: large;
padding-bottom: 16px;
border-bottom: 2px solid #A9A9A9;
margin-bottom: 10px;
white-space: nowrap;
}
.headers
{
text-align: left;
padding-right: 10px;
}
.numbers
{
text-align: right;
padding-right: 12px;
}
.textData
{
text-align: left;
padding-right: 10px;
}
.numbersHeader
{
width: 80px;
}
.numbersfooter
{
background-color: #d2d0d0;
color: #000000;
}
.SGridView
{
width: 100%;
}
.style1
{
height: 30px;
}
</style>
<asp:Literal ID="LtrMessage" runat="server"></asp:Literal>
<table style="padding-top: 9px">
<tr>
<td style="padding-bottom: 13px; font-style: normal;">
<strong>City :</strong><span style="color: Red; padding-left: 2px;">*</span>
</td>
<td>
<div id="divCustomCheckBoxList" runat="server" onmouseover="clearTimeout(timoutID);" onmouseout="timoutID = setTimeout(‘HideMList()’, 750);">
<table>
<tr>
<td align="right" class="style1">
<input id="txtSelectedMLValues" type="text" readonly="readonly" onclick="ShowMList()"
style="width: 150px;" runat="server" />
</td>
<td align="left" class="style1">
<img id="imgShowHide" runat="server" align="left" onclick="ShowMList()" src="~/_layouts/1033/images/down-arrow.bmp" />
</td>
</tr>
<tr>
<td colspan="2" class="DropDownLook">
<div>
<div runat="server" id="divCheckBoxListClose" class="DivClose">
<label runat="server" onclick="HideMList();" class="LabelClose" id="lblClose">
<b>x</b>
</label>
</div>

<div runat="server" title="divCheckBoxList" id="divCheckBoxList" class="DivCheckBoxList">
<asp:UpdatePanel ID="UpdatePanel11" runat="server">
<ContentTemplate>
<asp:CheckBox ID="CheckBoxList1" runat="server" Text="All" AutoPostBack="true" OnCheckedChanged="CheckBoxList1_CheckedChanged">
</asp:CheckBox>
<asp:CheckBoxList ID="lstMultipleValues" runat="server" Width="250px" CssClass="CheckBoxList">
</asp:CheckBoxList>
</ContentTemplate>
</asp:UpdatePanel>

</div>
</div>
</div>
</td>
<td>
</td>
</tr>
</table>
<br />
<br />
<div>
</div>
<div>
<script type="text/javascript">
var timoutID;

//This function shows the checkboxlist

function ShowMList() {
var divRef = document.getElementById(“<%=divCheckBoxList.ClientID%>");
divRef.style.display = “block";
var divRefC = document.getElementById(“<%=divCheckBoxListClose.ClientID%>");
divRefC.style.display = “block";
}

//This function hides the checkboxlist

function HideMList() {
document.getElementById(“<%=divCheckBoxList.ClientID%>").style.display = “none";
document.getElementById(“<%=divCheckBoxListClose.ClientID%>").style.display = “none";
}

var cblstTable;
var checkBoxPrefix;
var noOfOptions;
var selectedText

function FindSelectedItems(sender, textBoxID) {
cblstTable = document.getElementById(sender.id);
var flagUnchecked = 0;
var flaChecked = 0;
checkBoxPrefix = sender.id + “_";
noOfOptions = cblstTable.rows.length;
selectedText = “";
for (i = 0; i < noOfOptions; ++i) {
if (document.getElementById(checkBoxPrefix + i).checked) {
flag = 1;

if (selectedText == “")
{
selectedText = document.getElementById
(checkBoxPrefix + i).parentNode.innerText;
}
else
{
selectedText = selectedText + “," +
document.getElementById(checkBoxPrefix + i).parentNode.innerText;
}
}

for (i = 0; i < noOfOptions; ++i) {
if (document.getElementById(checkBoxPrefix + i).checked == false) {
document.getElementById(“<%=CheckBoxList1.ClientID%>").checked = false;
}

if (document.getElementById(checkBoxPrefix + i).checked == true) {
flagUnchecked = 1;
flaChecked = flaChecked + 1;
}
}
document.getElementById(textBoxID.id).value = selectedText;
if (flagUnchecked == 0) {
document.getElementById(textBoxID.id).value = “Select City";
}
if (flaChecked == noOfOptions) {
document.getElementById(“<%=CheckBoxList1.ClientID%>").checked = true;
document.getElementById(textBoxID.id).value = “All City";
}
}

function FindAllRepMgr(sender, textBoxID) {
if (document.getElementById(“<%=CheckBoxList1.ClientID%>").checked == true) {
for (i = 0; i < noOfOptions; ++i) {
var raw = document.getElementById(checkBoxPrefix + i).rawValue = null;
var raw1 = document.getElementById(checkBoxPrefix + i).checked = true;
document.getElementById(checkBoxPrefix + i).checked == true;
}
document.getElementById(textBoxID.id).value = “All City";
}
if (document.getElementById(“<%=CheckBoxList1.ClientID%>").checked == false) {
for (i = 0; i < noOfOptions; ++i) {
var raw = document.getElementById(checkBoxPrefix + i).rawValue = null;
var raw1 = document.getElementById(checkBoxPrefix + i).checked = false;
document.getElementById(checkBoxPrefix + i).checked == false;
}
document.getElementById(textBoxID.id).value = “Select City";
}
}
</script>
</div>
Dropdown list with multiple selection option in SharePoint 2010
Dropdown list with multiple selection option in SharePoint 2013

Get user profile properties using JavaScript object model in SharePoint

Now, we will see how to get user profile properties in SharePoint using JavaScript. We need to pass the user profile information let’s say Account Name, First Name, Last Name, PictureUrl, and SPS-SipAddress..etc to some other function in JavaScript object model in SharePoint.

For accessing current logged in user information you need to call GetUserProfileByName function of userprofileservice web service.

I have written a JavaScript code for accessing the GetUserProfileByName function of userprofileservice web service:

function fetchUserProfileData() {
var art = null;
//IE
if (window.ActiveXObject) {
art = new ActiveXObject("Microsoft.XMLHTTP");
}//Mozilla, chrome, etc.,
else if (window.XMLHttpRequest) {
art = new XMLHttpRequest();
}
else {
throw new Error("XMLHttpRequest not supported");
}
if (art == null) return null;
art.Open("POST", _spPageContextInfo.webAbsoluteUrl+ "/_vti_bin/userprofileservice.asmx", false);
art.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
art.setRequestHeader("SOAPAction", "http://microsoft.com/webservices/SharePointPortalServer/UserProfileService/GetUserProfileByName");

var Xsoap = "<?xml version=\"1.0\" encoding=\"utf-8\"?><soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:tns=\"http://schemas.microsoft.com/sharepoint/soap/\"><soap:Body><GetUserProfileByName xmlns=\"http://microsoft.com/webservices/SharePointPortalServer/UserProfileService\"><AccountName>Domain\\UserName</AccountName></GetUserProfileByName></soap:Body></soap:Envelope>";
art.Send(Xsoap);
var xmlDoc = art.responseXML;
alert(xmlDoc);
var strAccountSPSHireDate = "";

var elmValue = xmlDoc.getElementsByTagName("Value");
for (i = 0; i < elmValue.length; i++) {
if (elmValue[i].parentNode.parentNode.parentNode.childNodes[2].text =='SPS-HireDate‘) {
strAccountSPSHireDate = elmValue[i].childNodes[0].nodeValue;
}
}
alert(strAccountSPSHireDate);
}
</script>

List of User Properties (Use the GetPropertiesFor function for these):

  • AccountName
  • DirectReports
  • DisplayName
  • Email
  • ExtendedManagers
  • ExtendedReports
  • IsFollowed
  • LatestPost
  • Peers
  • PersonalUrl
  • PictureUrl”
  • Title
  • UserProfileProperties
  • UserUrl

List of User Profile Properties (Use the GetUserProfilePropertyFor function for these):

  • AboutMe
  • SPS-LastKeywordAdded
  • AccountName
  • SPS-Locale
  • ADGuid
  • SPS-Location
  • Assistant
  • SPS-MasterAccountName
  • CellPhone
  • SPS-MemberOf
  • Department
  • SPS-MUILanguages
  • EduExternalSyncState
  • SPS-MySiteUpgrade
  • EduOAuthTokenProviders
  • SPS-O15FirstRunExperience
  • EduPersonalSiteState
  • SPS-ObjectExists
  • EduUserRole
  • SPS-OWAUrl
  • Fax
  • SPS-PastProjects
  • FirstName
  • SPS-Peers
  • HomePhone
  • SPS-PersonalSiteCapabilities
  • LastName
  • SPS-PersonalSiteInstantiationState
  • Manager
  • SPS-PhoneticDisplayName
  • Office
  • SPS-PhoneticFirstName
  • PersonalSpace
  • SPS-PhoneticLastName
  • PictureURL
  • SPS-PrivacyActivity
  • PreferredName
  • SPS-PrivacyPeople
  • PublicSiteRedirect
  • SPS-ProxyAddresses
  • QuickLinks
  • SPS-RegionalSettings-FollowWeb
  • SID
  • SPS-RegionalSettings-Initialized
  • SISUserId
  • SPS-ResourceAccountName
  • SPS-AdjustHijriDays
  • SPS-ResourceSID
  • SPS-AltCalendarType
  • SPS-Responsibility
  • SPS-Birthday
  • SPS-SavedAccountName
  • SPS-CalendarType
  • SPS-SavedSID
  • SPS-ClaimID
  • SPS-School
  • SPS-ClaimProviderID
  • SPS-ShowWeeks
  • SPS-ClaimProviderType
  • SPS-SipAddress
  • SPS-ContentLanguages
  • SPS-Skills
  • SPS-DataSource
  • SPS-SourceObjectDN
  • SPS-Department
  • SPS-StatusNotes
  • SPS-DisplayOrder
  • SPS-Time24
  • SPS-DistinguishedName
  • SPS-TimeZone
  • SPS-DontSuggestList
  • SPS-UserPrincipalName
  • SPS-Dotted-line
  • SPS-WorkDayEndHour
  • SPS-EmailOptin
  • SPS-WorkDayStartHour
  • SPS-FeedIdentifier
  • SPS-WorkDays
  • SPS-FirstDayOfWeek
  • Title
  • SPS-FirstWeekOfYear
  • UserName
  • SPS-HashTags
  • UserProfile_GUID
  • SPS-HireDate
  • WebSite
  • SPS-Interests
  • WorkEmail
  • SPS-JobTitle
  • WorkPhone
  • SPS-LastColleagueAdded

This is how we can get user profile properties using the JavaScript object model in SharePoint 2010.

SharePoint 2010: jQuery autocomplete textbox containing list items

Now, we will see how to use the jQuery UI AutoComplete widget to consume an SharePoint Web Service (Lists.asmx) that is JSON Serialized. Here we will use jQuery techniques to query a list via its web services and do something flash.

The Autocomplete widget is one of the widgets provided in jQuery UI and provides suggestions while you type into the field. jQuery UI is a free widget and interaction library built on top of the jQuery JavaScript Library, that you can use to build highly interactive web applications.

As you can see this is the kind of data that is searched for everyday in SharePoint (could I have accessed some kind of SharePoint API that returns real ones, sure but I knocked this up quickly).

Here I have add a Content Editor Web Part on my page and paste below javascript code:

<link href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css" rel="stylesheet"/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link href="/resources/demos/style.css" rel="stylesheet"/>
<script type="text/javascript">
$(document).ready(function()
{
var soapEnv = "<soapenv:Envelope xmlns:soapenv='http://schemas.xmlsoap.org/soap/envelope/'><soapenv:Body> <GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'><listName>Microsoft employees</listName><viewFields><ViewFields><FieldRef Name='Employee' /> </ViewFields></viewFields> </GetListItems> </soapenv:Body> </soapenv:Envelope>";
//Make a call to the List WebService using the SOAP envelope described above.
//The URL is fixed to a Specific Site Root. Feel free to change this
//to your own fixed root or do some jscript voodoo to figure out where
//Of course in 2010 you can do this with the Client Object Model, or hit
//the list rest Service and return json, so enabling jsonp cross site calls.
$.ajax({
url: "http://SvrName:7070/_vti_bin/lists.asmx",
type: "POST",
dataType: "xml",
data: soapEnv,
contentType: "text/xml; charset=\"utf-8\"",
success: function( xmlResponse ) {
var domElementArray=$( "z\\:row", xmlResponse );
var dataMap = domElementArray.map(function()
{
return {
value: $(this).attr(‘ows_Employee') ,
id: $(this).attr(‘ows_Employee')
};
});
var data = dataMap.get();

//Find the Sharepoint Portal Search Box (this is a poor selector, but it is not properly named by sharepoint, well it is but INamingContainer getrs in the way)
$( "#tags" ).autocomplete(
{ source: data
});
}

});//.ajax

});//docReady

</script>

<div class="ui-widget">
<label for="tags"> Microsoft employees</label>
<input id="tags">
</div>

This could easily be additional page head stuff or master page stuff or in 2010 a custom action for script etc, but here it’s a CEWP.

Some of the prerequisites for using jQuery UI Autocomplete are:

  • jQuery Library: Can be downloaded from CDN (Content Delivery Network: http://code.jquery.com/jquery-1.9.1.js) or one can give link directly.
  • jQuery UI Library: Can be downloaded from CDN (Content Delivery http://code.jquery.com/ui/1.10.4/jquery-ui.js) or one can give link directly.
  • jQuery UI CSS: Can be downloaded from CDN (Content Delivery http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css) or one can give link directly.

Autocomplete column. It would look like this:

SharePoint 2010 Jquery autocomplete textbox containing list items

You may like following SharePoint JavaScript tutorials:

free sharepoint training

SharePoint Online FREE Training

JOIN a FREE SharePoint Video Course (3 Part Video Series)

envelope
envelope

Sagar Pardeshi

I am Developer working on Microsoft Technologies for the past 6+years. I am very much passionate about programming and my core skills are SharePoint, ASP.NET & C#,Jquery,Javascript,REST. I am running this blog to share my experience & learning with the community I am an MCP, MCTS .NET & Sharepoint 2010, MCPD Sharepoint 2010, and MCSD HTML 5,Sharepoint 2013 Core Solutions. I am currently working on Sharepoint 2010, MOSS 2007, Sharepoint 2013,Sharepoint 2013 App Dev, C#, ASP.NET, and SQL Server 2008.

>