SharePoint Online jsom examples (47 Examples)

Want to know how to work with jsom SharePoint? Check out various sharepoint javascript examples. Let us see the best 47 SharePoint Online jsom examples.

Here we will discuss how to use the javascript client object model in SharePoint 2013. In some other posts, we will see some jsom SharePoint 2013 examples. This is also known as ECMAScript Client Object Model (jsom) or JavaScript Client Object Model (JSOM) in SharePoint 2013. JSOM is used for accessing and manipulating SharePoint objects by using JavaScript (JavaScript) in an asynchronous manner.

If you are working with a SharePoint-hosted add-in, then we have to use Jsom in SharePoint-hosted Add-in. We can use jsom code inside a script editor web part, content editor web part, inside an HTML page or we can use it in SharePoint Add-in.

Table of Contents

JavaScript Client Object Model (JSOM) in SharePoint

To work with JSOM we need to refer to certain javascript files and if your web part page or the page is using the default master pages then we do not need to give any reference because in most cases the reference is already presented inside the master pages. And we should also make sure that there should be one and only reference that exists for a particular file.

We can write the JSOM code inside a script editor or also inside a content editor web part inside a SharePoint Site. But Cross-site scripting is also not allowed in JSOM like you cannot call SharePoint objects from one site to another site.

Below are the browsers supported like:

  • IE 7.0 onwards
  • Firefox 3.5 onwards
  • Safari 4.0 onwards.
  • Google Chrome

When the client made an Http request to the server, the server tries to load the page and the master page. If the page uses the default master pages then the page already has references to the required JSOM scripts.

If it is a custom master page, then we have to load the JSOM references before the pages and controls can use the JSOM.

SharePoint downloads the files from the C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\TEMPLATE\LAYOUTS directory to the client browser.

The js files which we required are:

  • SP.js
  • SP.Core.js
  • SP.Runtime.js

Unlike SharePoint 2007, SharePoint 2010 or 2013 versions SharePoint only download the required files instead of downloading the whole file. SharePoint provides Script On Demand (SOD) framework which ensures that only the required files are downloaded to the client and provides options to load them in the background after the page has completed loading.

SOD is a class defined in the init.js file and contains methods for loading scripts, registering script dependencies, executing methods within a loaded page, and event notification.

You can enable on-demand loading is to set the OnDemand=”true” attribute in the SharePoint:ScriptLink server tag.

<script type="text/javascript">
SP.SOD.RegisterSod("SP.js", "\_layouts\SP.js");
</script>

If you want to give reference in a page that is using any custom master page, then you can write like below:

<SharePoint:ScriptLink ID="ScriptLink21" Name="sp.js" runat="server" OnDemand="false" LoadAfterUI="true" Localizable="false" />

crud operations using jsom in SharePoint online

Let us check out an example on crud operations using jsom in sharepoint online.

Here I have a custom SharePoint Online list which has two columns: Title and Description. But the same code also you can use to create, update and delete list items by using jsom in SharePoint Online.

Create a List item using JSOM in SharePoint

Now, we will see, how to create a list item using Jsom (JacvaScript object model) in SharePoint Online or SharePoint 2013/2016/2019.

The below jsom code you can write in a script editor web part or also you can use inside a SharePoint hosted add-in or apps.

<script language="javascript" type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(createListItem,'sp.js'); 

function createListItem() {
var clientContext = new SP.ClientContext.get_current();

var list = clientContext.get_web().get_lists().getByTitle('MyCustomList');
var itemInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(itemInfo);
listItem.set_item('Title', 'Item-1');
listItem.set_item('Description', 'Item-1 Description');
listItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
alert('Item created successfully !');
}

function onQueryFailed(sender, args) {
alert('Could not able to update item: ' + args.get_message());
}
</script>

Once you run the code, then you can see the list item will be created using jsom like below:

javascript add item to list
javascript add item to list

The above code we can use to add item to list using javascript in SharePoint.

Insert item to SharePoint list using jsom (dynamically)

In the previous example, we saw how to insert item to SharePoint list using JavaScript. But the data which we were inserting was static.

We can also make it dynamic, here in this example, I have added a textbox and a button and on the button click we are saving the textbox value to the SharePoint list.

Add the below JSOM code inside a script editor web part in SharePoint Online or SharePoint web part page.

<input id="txtTitle" name="txtTitle" type="text" />

<input name="ADD" id="btnAdd" type="submit" value="Add Item to List" />
<script language="javascript" type="text/javascript">

$(document).ready(function () {

$("#btnAdd").click(function () {
var title = $("#txtTitle").val();
AddListItem(title);
});
});
function AddListItem(TitleField) {
var ListName = "Employee";
var context = new SP.ClientContext.get_current();
var lstObject = context.get_web().get_lists().getByTitle(ListName);
var listItemCreationInfo = new SP.ListItemCreationInformation();
var newItem = lstObject.addItem(listItemCreationInfo);
newItem.set_item('Title', TitleField);
newItem.update();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
alert('Item created');
}
function onFailure(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

This is how we can insert data to the SharePoint list using javascript object model (jsom) in SharePoint.

Update List item using JSOM in SharePoint Online

Now, we will see how to update the list item using the javascript object model (jsom) code. Here I have taken the list item id hardcoded.

Here we will update the list item whose ID=2.

<script language="javascript" type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(updateListItem,'sp.js'); 

function updateListItem() {
var clientContext = new SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('MyCustomList');
var listItem = list.getItemById(2);
listItem.set_item('Title', 'Updated List Item Title');
listItem.set_item('Description', 'Updated List Item Description');
listItem.update();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
alert('Item updated successfully !');
}

function onQueryFailed(sender, args) {
alert('Could not able to update item: ' + args.get_message());
}
</script>

Like create list item code, you can also use the update list item code inside a script editor or content editor web part in a web part page in SharePoint.

The output will come like below:

create update and delete list items using javascript object model
javascript update list item

The above code is an example of a sharepoint javascript update list item.

Delete List item using JavaScript Object Model (JSOM) in SharePoint

Now, we will see how we can delete a list item using jsom in SharePoint. The same code we can use to delete SharePoint list item using jsom in SharePoint 2013/2016/2019.

Here we will delete the list item whose id =2.

<script language="javascript" type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(deleteListItem,'sp.js'); 

function deleteListItem() {
var clientContext = new SP.ClientContext.get_current();
var list = clientContext.get_web().get_lists().getByTitle('MyCustomList');
var listItem = list.getItemById(2);
listItem.deleteObject();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
alert('Item deleted');
}

function onQueryFailed(sender, args) {
alert('Could not able to delete item: ' + args.get_message());
}

</script>

Once you run the code, you can see the item will be deleted from the SharePoint list. This is how we can delete an item from a SharePoint list using javascript object model.

create update and delete list items using jsom sharepoint
delete list item javascript

The above code will delete a single item, but if you want to delete all items from a SharePoint list, then you can read a tutorial on Different ways to delete all items from SharePoint list.

Display SharePoint list items using JSOM

Now, we will see how to retrieve list items from the SharePoint list using the JavaScript object model (jsom) in SharePoint Online Office 365 sites.

The same code also works for SharePoint Online as well as SharePoint 2013/2016.

In this particular example, I have a SharePoint Online list that has columns like:

  • Title
  • FirstName
  • LastName

And in that SharePoint list, there were few records inside it. The out of box list looks like below:

display list items using jsom in SharePoint
display list items using jsom in SharePoint

Here we will show try to retrieve this list data by using jsom.

Here let us put our jsom code inside a script editor web part or content editor web part, which we will add inside a web part page in SharePoint.

Below is the full jsom code to display the SharePoint list items using JSOM.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<div id="divListItems"></div>
<script>
$(function () {
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
});
var collListItem;
function retrieveListItems() {
var clientContext = new SP.ClientContext();
var oList = clientContext.get_web().get_lists().getByTitle('Employees');
var camlQuery = new SP.CamlQuery();
collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded(sender, args) {
var listItemInfo = ";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
listItemInfo += '<strong>ID: </strong> ' + oListItem.get_id() +
' <strong>Title:</strong> ' + oListItem.get_item('Title') +
' <strong>FirstName:</strong> ' + oListItem.get_item('FirstName') +
' <strong>LastName:</strong> ' + oListItem.get_item('LastName') +
'<br />';
}
$("#divListItems").html(listItemInfo);
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}
</script>

If you save the code and refresh the page you can see the list items below:

display list items using javascript in SharePoint
sharepoint jsom get list items

Here we have passed an empty caml query.

var camlQuery = new SP.CamlQuery();
this.collListItem = oList.getItems(camlQuery);

But if you want to retrieve items based on certain filter conditions then you can write the CAML query and can pass it like below:

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(
'<View><Query><Where><Geq><FieldRef Name=\'ID\'/>' +
'<Value Type=\'Number\'>2</Value></Geq></Where></Query>' +
'<RowLimit>10</RowLimit></View>'
);

var collListItem = oList.getItems(camlQuery);

The above query will return results where the ID value greater than or equal to 2.

This is how we can display SharePoint list items using the JavaScript object model (jsom).

SharePoint Online jsom examples

Now, let us check out a few jsom examples in SharePoint Online.

Example-1: Create List using JSOM SharePoint Online

Now to work with the SharePoint objects from JSOM, first we need an instance of the client context. You can get an instance of SP.ClientContext by using the get_current() method. Like

var clientContext = SP.ClientContext.get_current();

Below is the code to create a List in the site in SharePoint 2013 or SharePoint online:

<input type='button' id='id1′ value='Create List' onclick="CreateList();"/>

<script type="text/javascript">
function CreateList()
{
var clientContext;
var listCreationInfo;
var web;
var list;

clientContext = SP.ClientContext.get_current();
web = clientContext.get_web();
listCreationInfo = new SP.ListCreationInformation();
listCreationInfo.set_title("MyTestList");
listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
list = web.get_lists().add(listCreationInfo);

clientContext.load(list);

clientContext.executeQueryAsync(
function () { alert("Site Created Successfully!!!") },
function () { alert("Request failed") }
);
}
</script>

Go to the site content and you will be able to see the list created.

Example-2: Add list item to SharePoint Online List using JSOM

Here we will try to create one list item from JSOM SharePoint 2013 or SharePoint online.

<input type='button' id='id1′ value='Create List Item' onclick="CreateListItem();"/>

<script type="text/javascript">
var siteUrl = 'http://win-pfcp2dgt8di/sites/EnjoySharePoint/';
function CreateListItem() {
var clientContext = new SP.ClientContext(siteUrl);
var oList = clientContext.get_web().get_lists().getByTitle('MyTestList');
var itemCreateInfo = new SP.ListItemCreationInformation();
this.oListItem = oList.addItem(itemCreateInfo);
oListItem.set_item('Title', 'My test item');
oListItem.update();
clientContext.load(oListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
alert('Item created: ' + oListItem.get_id());
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

Example-3: Get Users from SharePoint Group using JavaScript Client Object Model (JSOM)

Here we will see how to retrieve users from SharePoint group using the JavaScript client object model. Put the below code in a Script editor web part inside a web part page in SharePoint. It will download all the users from a particular group.


<input type="button" id="btnUpdate" value="Export Site Users" onclick="GenerateReport();" />

<script type="text/javascript">
var siteUrl = 'http://win-pfcp2dgt8di/sites/EnjoySharePoint/';
var groups=['20'];
var gp_users=[];
var gp_name;

function GenerateReport()
{
retrieveAllUsersInGroup('20');
}

function retrieveAllUsersInGroup(grp) {

var clientContext = new SP.ClientContext(siteUrl);
var collGroup = clientContext.get_web().get_siteGroups();
var oGroup = collGroup.getById(grp);
this.collUser = oGroup.get_users();
clientContext.load(collUser);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded() {
var userInfo = ";
var userEnumerator = collUser.getEnumerator();
while (userEnumerator.moveNext()) {
var oUser = userEnumerator.get_current();

userInfo += '\nUser: ' + oUser.get_title() +
'\nID: ' + oUser.get_id() +
'\nEmail: ' + oUser.get_email() +
'\nLogin Name: ' + oUser.get_loginName();
gp_users.push(oUser.get_title());
}
generateexcel();
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

}

function generateexcel() {

for(z=0;z < gp_users.length;z++)
{
var table = document.getElementById('usrTable');
var row = table.insertRow(1);
var cell1 = row.insertCell(0);

cell1.innerHTML =gp_users[z]

}
var x = document.getElementById('usrTable').rows;
var xls = new ActiveXObject(“Excel.Application");
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.cells(i + 1, j + 1).value = y[j].innerText;
}
}
window.location.href="http://win-pfcp2dgt8di/sites/EnjoySharePoint/";
}
</script>
<table id="usrTable" border="1″ style="display:none;">
<tbody>
<tr width='250px'>
<th>Name</th>
</tr>
</tbody>
</table>

Example-4: Get current logged in user name in SharePoint online using JSOM

Now, we will see how to get the current logged in username in SharePoint online using JavaScript object model (jsom).

To retrieve the username, insert the below code inside a script editor web part. Here I am displaying the username on a button click.

<script type="text/javascript">
function GetCurrentUserName()
{
alert(_spPageContextInfo.userLoginName);
}
</script>

<input type='button' value='Submit' onclick="GetCurrentUserName();"/>

Example-5: Fetch List view using JavaScript object model (jsom) in SharePoint Online

Now, we will see how to fetch list view data using the JavaScript object model (jsom) in SharePoint 2013/2016 or SharePoint Online.

Below is the full jsom code to fetch list view using jsom in SharePoint. You can add the code in a script editor web part in a SharePoint web part page.

Here I have a list as Testing123 which has a view as All Items.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<script language="javascript" type="text/javascript">

ExecuteOrDelayUntilScriptLoaded(getMyList,'sp.js');
function getMyList() {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_web();
var list = web.get_lists().getByTitle("Testing123");
var views = list.get_views();
var view = views.getByTitle("All Items");
view.update();
ctx.load(view);
myview = view.renderAsHtml();
ctx.executeQueryAsync(OnSuccess, OnFailure);
}

function OnSuccess() {
myview = myview.get_value().toString();
$("#testingdata").append(myview);
}
function OnFailure() {
}
</script>

<div id='testingdata'></div>

This is how we can fetch list view using the JavaScript object model (jsom) in SharePoint Online/2013/2016.

Example-6: Create subsite in SharePoint Online using JavaScript

Now, let us see how to create a SharePoint subsite using jQuery and JavaScript client object model in SharePoint 2016, SharePoint 2013 or SharePoint Online.

We will also see, how to get all SharePoint subsites using the JavaScript object model (jsom).

The code will work in SharePoint 2016/2013 and SharePoint Online also. You can directly put the below code inside a script editor web part on a web part page in SharePoint.

As you can see here I am taking one textbox and I am using the value for the site name, description as well as the URL.

<h1>Create Site</h1>

Site Name: <input type="text" name="txtSitename" id="txtSitename">
<input type="submit" value="Submit" id="btnCreateSite">

<script type="text/javascript">

$("#btnCreateSite").click(function(){
CreateWebsite($("#txtSitename").val(), $("#txtSitename").val(), $("#txtSitename").val(), "BLANKINTERNET#2");
});

function CreateWebsite(title, description, webUrl, templateTitle)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
context.load(web);
var webTemplates = web.getAvailableWebTemplates(1033,false);
context.load(webTemplates);
context.executeQueryAsync(function(){
var enumerator = webTemplates.getEnumerator();
var customTemplate;
while(enumerator.moveNext())
{
var webTemplate = enumerator.get_current();
var webTitle = webTemplate.get_title();
if(webTitle == templateTitle)
{
customTemplate = webTemplate.get_name();
break;
}
}
var webCreationInformation = new SP.WebCreationInformation();
webCreationInformation.set_title(title);
webCreationInformation.set_description(description);
webCreationInformation.set_language(1033);
webCreationInformation.set_url(webUrl);
webCreationInformation.set_useSamePermissionsAsParentSite(true);
webCreationInformation.set_webTemplate(customTemplate);
var newWeb= web.get_webs().add(webCreationInformation);
context.executeQueryAsync(function(){
alert(‘Website created successfully.’);
},
function(sender, args){
alert(args.get_message());
});
},
function(sender, args){
alert(args.get_message())
}
);
}
</script>

Give a name and click on Submit button which will create a sub site under the site.

Another Example:

Here, I have created an HTML textbox and a button where the user will provide a site name and click on the button to create a subsite and page using the JavaScript object model (jsom) in SharePoint 2013/2016 or SharePoint Online.

Title: <input type="text" id="txtSitename" /> &nbsp <button type="button" id="btnCreateSite" >Create</button>

<script type="text/javascript" src="/sites/Intranet/Style%20Library/aaa/jquery-1.8.3.min.js" ></script>
<script type="text/javascript" src="/_layouts/15/SP.Runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/SP.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.publishing.js"></script>

<script type="text/javascript">

$("#btnCreateSite").click(function(){
CreateWebsite($("#txtSitename").val(), $("#txtSitename").val(), $("#txtSitename").val(), "BLANKINTERNET#2");
});

var context;
var web;
var newWeb;
function CreateWebsite(title, description, webUrl, templateTitle)
{
context = new SP.ClientContext.get_current();
web = context.get_web();
context.load(web);
var webTemplates = web.getAvailableWebTemplates(1033,false);
context.load(webTemplates);
context.executeQueryAsync(function(){
var enumerator = webTemplates.getEnumerator();
var customTemplate;
while(enumerator.moveNext())
{
var webTemplate = enumerator.get_current();
var webTitle = webTemplate.get_title();
if(webTitle == templateTitle)
{
customTemplate = webTemplate.get_name();
break;
}
}
var webCreationInformation = new SP.WebCreationInformation();
webCreationInformation.set_title(title);
webCreationInformation.set_description(description);
webCreationInformation.set_language(1033);
webCreationInformation.set_url(webUrl);
webCreationInformation.set_useSamePermissionsAsParentSite(true);
webCreationInformation.set_webTemplate(customTemplate);
newWeb= web.get_webs().add(webCreationInformation);
context.executeQueryAsync(function(){
createPublishingPage("Home.aspx", "blankWebPartPage.aspx")
alert('Website created successfully.');
},
function(sender, args){
alert(args.get_message());
});
},
function(sender, args){
alert(args.get_message())
}
);
}

function loadPageLayout (pageLayoutName, callback) {
var pageFromDocLayout, pageLayoutItem;

SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function () {
context = SP.ClientContext.get_current();
var site = context.get_site();

context.executeQueryAsync(function () {
var rootWeb = site.get_rootWeb();
context.load(rootWeb, 'ServerRelativeUrl');

context.executeQueryAsync(function () {
var rootUrl = rootWeb.get_serverRelativeUrl();
pageFromDocLayout = rootWeb.getFileByServerRelativeUrl(rootUrl + "_catalogs/masterpage/" + pageLayoutName);

context.executeQueryAsync(function () {
pageLayoutItem = pageFromDocLayout.get_listItemAllFields();

context.executeQueryAsync(function () {
if (typeof callback == "function") {
callback(pageLayoutItem);
}
});
});
});
});
});
};

function createPublishingPage (filename, pageLayoutName, callback) {
SP.SOD.executeFunc('SP.js', 'SP.ClientContext', function () {
SP.SOD.executeFunc('SP.Publishing.js', 'SP.Publishing.PublishingWeb', function () {
var pubWeb, pageInfo, newPage, listItem;
//context = new SP.ClientContext('/sites/Intranet');

//web = currWeb;
context.load(newWeb);
context.executeQueryAsync(function () {
pubWeb = SP.Publishing.PublishingWeb.getPublishingWeb(context, newWeb);
context.load(newWeb);
context.load(pubWeb);
context.executeQueryAsync(function () {

// load page layout and create the new page
loadPageLayout(pageLayoutName, function (pageLayoutItem) {
pageInfo = new SP.Publishing.PublishingPageInformation();
pageInfo.set_pageLayoutListItem(pageLayoutItem);
pageInfo.set_name(filename);

newPage = pubWeb.addPublishingPage(pageInfo);

context.load(newPage);

context.executeQueryAsync(function () {
// Success callback after adding a new Publishing Page.
// We want to get the actual list item that is represented by the Publishing Page.
listItem = newPage.get_listItem();
context.load(listItem);

context.executeQueryAsync(

// Success callback after getting the actual list item that is
// represented by the Publishing Page.
// We can now get its FieldValues, one of which is its FileLeafRef value.
// We can then use that value to build the Url to the new page
// and set the href or our link to that Url.
function () {
if (typeof callback == "function") {
callback(listItem);
}
},

// Failure callback after getting the actual list item that is
// represented by the Publishing Page.
function (sender, args) {
alert('Failed to get new page: ' + args.get_message());
}
);
},
// Failure callback after trying to add a new Publishing Page.
function (sender, args) {
alert('Failed to Add Page: ' + args.get_message());
}
);
});
},
// Failure callback after trying to get the host Web as a PublishingWeb.
function (sender, args) {
alert('Failed to get the PublishingWeb: ' + args.get_message());
});
});
});
});

}

</script>

Example-7: Get all SharePoint subsites using JavaScript

Now, we will see how to get all SharePoint subsites using JavaScript object model (jsom).

To use the code, create a web part page and a content editor webpart or script editor web part and add the below code.

ontext = new SP.ClientContext.get_current();
currentweb = currentcontext.get_web();
//this.subsites = currentweb.get_webs();
this.subsites = currentweb.getSubwebsForCurrentUser(null);
currentcontext.load(this.subsites);
currentcontext.executeQueryAsync(Function.createDelegate(this, this.ExecuteOnSuccess),
Function.createDelegate(this, this.ExecuteOnFailure));
}

function ExecuteOnSuccess(sender, args) {
var subsites = ";
var enum1 = this.subsites.getEnumerator();
var el = document.getElementById(‘LKMSubWebs');
while (enum1.moveNext())
{
var Site = enum1.get_current();
subsites += ‘\n' + ‘<a class=subsitecls href='+ Site.get_serverRelativeUrl()+'>'+Site.get_title()+'</a> </br>'
//RootElement.append(‘<a class=subsitecls href='+ siteTitle+'>'+siteTitle+'</a> </br>');
//alert(subsites);
}
el.innerHTML = subsites;
}

function ExecuteOnFailure(sender, args) {
alert("error");
//alert(args.get_message());
}
</script>

<div id="LKMSubWebs"></div>

This will bind all the SharePoint subsites titles and will display them.

Example-8: Retrieve alternative languages in SharePoint using JavaScript

Now, let us see, how to retrieve alternative languages from language settings in SharePoint Online using the JavaScript object model (jsom). In the same way, we can get alternative languages in SharePoint 2013/2016 using JavaScript.

Retrieve alternative languages in SharePoint using JavaScript

You can see the alternative languages from Site settings -> language settings that are under Site Administration. It shows like below:

jsom sharepoint
jsom sharepoint

For this particular post, I have added the below code inside a script editor web part on a SharePoint web part page.

Remember it will display like for the English language it will return 1033.

<input type="button" id="btnGetLanguages" value="Click Here"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(“#btnGetLanguages").click(function(){
GetLanguages();
});
});

var web;
function GetLanguages(){
var clientContext = new SP.ClientContext();
web=clientContext.get_web();
clientContext.load(web,"SupportedUILanguageIds");
clientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}

function onSuccess() {
var supportedlanguage = web.get_supportedUILanguageIds();
for (var i = 0; i < supportedlanguage.length; i++) {
var languageName = supportedlanguage[i].toString();
alert(languageName);
}
}
function onFailure(sender, args) {
alert(‘Error Occurred. ‘ + args.get_message());
}
</script>

This is how to get alternative languages in SharePoint Online or SharePoint 2013/2016 using the JavaScript object model (jsom).

Example-9: Create and delete SharePoint list using JavaScript Object Model (JSOM)

Here I will explain how to create, and delete the SharePoint list using the Javascript object model (jsom).

Create SharePoint list using JavaScript Object Model (JSOM)

Here we will create our HTML and JS file using SharePoint Designer 2013. Open Sharepoint Designer. Create .HTML file under the SiteAssets folder.

create sharepoint list using jsom
create sharepoint list using jsom

Add the necessary scripts to the top of the HTML file to create a sharepoint list.

Then Add one text input box to get the list title and Add one Input button to create an action.

create list jsom sharepoint 2016
create list jsom sharepoint

Lets add some piece of code to create a list
Scripts:

<script src="_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="_layouts/15/sp.js" type="text/javascript"></script>
<script src=" /SiteAssets/JS/CRUD list.js" type="text/ javascript"></script>

HTML:

<div id="form">
<table>
<tr>
<td>
<p>Enter List Name</p>
</td>
<td>
<input type="text" id="txtlistname" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btncreate" value="submit" />
</td>
</tr>
</table>
</div>
<div id="results"></div>

CreateList.js

Create a function named “btncreate”

Note:- Using this function am get the value of the list name from the HTML input box on button click event. Then pass the list value into another function “CreateList”

Code:

function btncreate()
{
$('#btncreate').on("click", function () {
var listValue = $('#txtlistname').val();
CreateList(listValue);
});
}

Code

function CreateList(listValue)
{
var context = new SP.ClientContext() // Get the site collection from the context
var web = context.get_web(); // Get all the list properties
var listcreation = new SP.ListCreationInformation(); // Used for create a list
listcreation.set_title(listValue); // get the title of the list
listcreation.set_templateType(SP.ListTemplateType.genericList) // Provide the template for list ex:announcement, task in this scenario used genericlistproperty
this.list = web.get_lists().add(listcreation); // Create a list using web property
context.load(list); // load the values into the site context
context.executeQueryAsync(
Function.createDelegate(this, this.onsuccess),
Function.createDelegate(this, this.onfailed)
);
}

function onsuccess()
{
var results = list.get_title() + 'Create success'; // if success message will be rendered into html element
$('#results').html(results);
}
function onfailed(sender, args){
alert('Creation Failed' + args.get_message() + '\n' +args.get_stackTrace()); // If failed shows error message
}

Full Code

$(function () {
btncreate();
});

function btncreate()
{
$('#btncreate').on("click", function () {
var listValue = $('#txtlistname').val();
CreateList(listValue);
});
}

function CreateList(listValue)
{
var context = new SP.ClientContext()
var web = context.get_web();
var listcreation = new SP.ListCreationInformation();
listcreation.set_title(listValue);
listcreation.set_templateType(SP.ListTemplateType.genericList)
this.list = web.get_lists().add(listcreation);
context.load(list);
context.executeQueryAsync(
Function.createDelegate(this, this.onsuccess),
Function.createDelegate(this, this.onfailed)
);
}

function onsuccess()
{
var results = list.get_title() + 'Create success';
$('#results').html(results);
}
function onfailed(sender, args){
alert('Creation Failed' + args.get_message() + '\n' +args.get_stackTrace());
}

Final Result:

create list jsom sharepoint online
create list jsom sharepoint online

Now let’s go and delete a created sharepoint list.

Delete SharePoint list using JavaScript Object Model (JSOM)

HTML:

<div id="form">
<table>
<tr>
<td>
<p>Enter List Name</p>
</td>
<td>
<input type="text" id="txtlistname" />
</td>
</tr>
<tr>
<td>
<input type="button" id="btncreate" value="submit" />
<input type="button" id="btndelete" value="delete" />
</td>
</tr>
</table>
</div>
<div id="results"></div>

Scripts:

<script src="_layouts/15/sp.runtime.js" type="text/javascript"></script>
<script src="_layouts/15/sp.js" type="text/javascript"></script>
<script src=" SiteAssets/JS/DeleteList.js" type="text/javascript"></script>

DeleteList.js

$( function () {
btndelete()
});

function btndelete()
{
$('#btndelete').on("click", function () {
var listValue = $('#txtlistname').val();
DeleteList(listValue);
});
}

function DeleteList(listValue)
{
var context = new SP.ClientContext();
var web = context.get_web();
this.list = web.get_lists().getByTitle(listValue);
list.deleteObject(); // Delete the created list from the site
context.executeQueryAsync(
Function.createDelegate(this, this.ondeletesuccess),
Function.createDelegate(this, this.ondeletefailed)
);
}

function ondeletesuccess()
{
$('#results').html("List deleted successfully"); // on success bind the results in HTML code
}

function ondeletefailed(sender, args){
alert('Delete Failed' + args.get_message() + '\n' +args.get_stackTrace()); // display the errot details if deletion failed
}

Final result:

delete list jsom sharepoint online
delete list jsom sharepoint online

This is how to create and delete SharePoint list using the JavaScript Object Model (JSOM).

Example-10: Add Column using JavaScript in SharePoint Online

Let us see, how to create fields or columns in a SharePoint list using JSOM (javascript client object model) in SharePoint Online. The same jsom code we can use to create columns in SharePoint 2013/2016 list also.

Create columns in SharePoint Online list using JavaScript

Here we will add columns to a custom list using jsom in SharePoint Online. Here we will design an HTML form, where we will provide options to the user an input form to enter column name, data type and description, and a submit button.

Once the user fills in the details like column name, data type, and description and clicks on Submit, the column will be created or added to the SharePoint custom list.

So we have added an HTML form and added the input controls like dropdown list, textbox, button, etc. And we will have a js file that will have the jsom code to create the column.

Here we have taken two text boxes one drop-down list and a submit button. Here I have hardcoded the dropdown values as the column types as Single line, multi-line, and number type. Have taken a <p> tag to display the success message. Below is HTML code:

<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://onlysharepoint2013.sharepoint.com/sites/Raju/SiteAssets/Bihusdevelopment2/creatingcolumns.js"></script>

<table>
<tr>
<td>
Display Name
</td>
<tdcolspan="4">
<inputtype="text"id="txtcolDisplayNmae">
</td>
</tr>
<tr>
<td>
columnsType
</td>
<tdcolspan="4">
<selectid="ddlcolumnstype">
<option>Single line</option>
<option>multi line</option>
<option>number</option>
</select>
</td>
</tr>
<tr>
<td>
Description
</td>
<tdcolspan="4">
<textarearows="4"cols="22"id="txtcolDescr"></textarea>
</td>
</tr>
<tr>
<tdcolspan="3">
</td>
<td>
<tdcolspan="4">
<inputtype="button"value="AddColumns"id="btncreatecol"></input>
</td>
</tr>
</table>

<p id="psuccess" align="center"></p>

I have created a custom list as “department” where the columns will be added.

Here we will take the inputs from the user like a type of Column, Display Name and description. We will retrieve all those inputs and bind using JSOM to create desired columns. Below is JSOM code to create Columns.

$(document).ready(function () {
$("#btncreatecol").click(function(){
retrievecolumnsTemplate();
});
});
function retrievecolumnsTemplate(){
var coldisplayname=$("#txtcolDisplayNmae").val();
var template=$('#ddlcolumnstype :selected').val();
var coldescription=$("#txtcolDescr").val();
var clientContext=newSP.ClientContext.get_current();
var oWebsite=clientContext.get_web();
oList = clientContext.get_web().get_lists().getByTitle('department');
varfldCollection=oList.get_fields();
if ( template=='multi line'){
varrichTextField=clientContext.castTo(
fldCollection.addFieldAsXml('<Field Type="Note" DisplayName=\"NewField\" Name="NewField" Required="False" NumLines="12" RichText="TRUE" AppendOnly="TRUE" />', true, SP.AddFieldOptions.addToDefaultContentType),SP.FieldMultiLineText);
richTextField.set_description(coldescription);
richTextField.set_title(coldisplayname);
richTextField.update();
}
elseif(template=='Single line' )
{
var singlelinetext=clientContext.castTo(
fldCollection.addFieldAsXml('<Field Type="Text" DisplayName=\"NewField\" Name="NewField" />', true,SP.AddFieldOptions.addToDefaultContentType),SP.FieldText);
singlelinetext.set_title(coldisplayname);
singlelinetext.set_description(coldescription);
singlelinetext.update();
}
elseif(template=='number')
{
var numberField=clientContext.castTo(
fldCollection.addFieldAsXml('<Field Type="Number" DisplayName=\"NewField\" Name="NewField" Required="False" />', true, SP.AddFieldOptions.addToDefaultContentType),SP.FieldNumber) ;
numberField.set_title(coldisplayname);
numberField.set_description(coldescription);
numberField.update();
}
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}
function onQuerySucceeded(sender, args) {
alert("column added");
    }
function onQueryFailed(sender, args) {
alert('Error: '+args.get_message() +'\n'+args.get_stackTrace());
}

As you can see in the below image Display Name, Column Type and description are provided and when we click on Add Column button a popup is displayed as Column is added.

Example-11: Get all SharePoint lists and libraries using JavaScript

In this SharePoint jsom tutorial, we will discuss, how to retrieve all lists and libraries from SharePoint site using the JavaScript object model (jsom) in SharePoint Online Office 365.

The same jsom code we can use to retrieve all lists and libraries from SharePoint 2013/2016 sites.

Get all SharePoint list and libraries using jsom

Here we have put the jsom code inside a script editor web part inside a web part page in the SharePoint site.

If you face one issue like Uncaught TypeError: SP.ClientContext is not a constructor error, then you can resolve by following this article.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<div id="divGetListData"></div>

<script>
$(function () {
ExecuteOrDelayUntilScriptLoaded(getAllLists, "sp.js");
});
var collList;
function getAllLists() {
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
collList = oWebsite.get_lists();
clientContext.load(collList);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
var listInfo = ";
var listEnumerator = collList.getEnumerator();
while (listEnumerator.moveNext()) {
var oList = listEnumerator.get_current();
listInfo += oList.get_title() + '<br />';
}
$("#divGetListData").html(listInfo);
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +
'\n' + args.get_stackTrace());
}

</script>

Once you will save this code it will display all the lists and libraries from the SharePoint site like below:

Get all SharePoint lists and libraries using JavaScript
Get all SharePoint lists and libraries using JavaScript

Here, we learned how to get all the list and libraries from the SharePoint site using the JavaScript object model (jsom).

Example-12: Create a file using JavaScript in SharePoint document library

Now, we will see how to create a file using the JavaScript object model (jsom) in SharePoint Online or SharePoint 2013/2016.

Here in this particular example let us take an HTML form that has a textbox, multiple text boxes as well as a button. Here the user will give a name for the file and the user can put the file content in the multiline textbox. Then the user can submit in the button which will create a text file in a SharePoint document library.

Here we will write both the HTML code as well as in the JavaScript object model (jsom) inside a script editor web part which will be inside a web part page in SharePoint. The HTML code will look like the below:

HTML Code:

<div id="CreateFile">
<div>
<strong>Enter a title for the document:</strong>
<br />
<input type="text" id="txtDocumentTitle" />
</div>
<div>
<strong>Enter content for the document:</strong>
<br />
<textarea cols="20" id="txtDocumentContent"></textarea>
</div>
<br />
<input type="button" id="btnSubmit" value="Submit" />
</div>
<div id="divResults"></div>

JSOM Code:

Below is the code to create a file in the document library using jsom.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createDocument();
});
}

function createDocument() {
var docTitle = $("#txtDocumentTitle").val() + ".txt";
var docContent = $("#txtDocumentContent").val();
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle("Documents");
var fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(docTitle);
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
for (var i = 0; i < docContent.length; i++) {
fileCreateInfo.get_content().append(docContent.charCodeAt(i));
}

this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
clientContext.load(this.newFile);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
$("#divResults").html("Document successfully created!");
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +'\n' + args.get_stackTrace());
}
</script>

Once we will Save the page you can see a page like below where user can give a title for the file, then the user can put content in the content textbox and then the user can click on the submit button which will create a file inside the SharePoint document library like below:

create file using jsom in sharepoint
sharepoint create file programmatically

Now you can check in the SharePoint document library where you can see the file got created in the document library.

create file using javascript in sharepoint online
sharepoint create file programmatically

This is how we can create a file inside a SharePoint document library using javascript.

Example-13: Read file content using JavaScript object model (jsom) in SharePoint

Now, we will see how to read file content from a document library using javascript in SharePoint.

Here we have taken a button, on click on that button we will read the content of the document and will display in a div. Here we will write both HTML and javascript object model code inside a script editor web part which we will add inside a SharePoint web part page.

HTML Code:

<input type="button" id="btnSubmit" value="Read Document" /><br />
<div id="divReadDocument" />

Jsom Code:

Below is the JSOM code to read content from a file that is presented in a SharePoint document library.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>

$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
readDocument();
});
}

function readDocument() {
var fullUrl = _spPageContextInfo.webAbsoluteUrl + "/Shared Documents/Bijay.txt";
$.ajax({
url: fullUrl,
type: "GET"
})

.done(function (data) {
$("#divReadDocument").html(data);
})
.fail(function () {
alert("error");
});
}
</script>

Once you will Save the page and click on the button, you can see the .txt file content like below:

read file content using javascript in sharepoint
get file content sharepoint javascript

This is how we can read file content using javascript object model (jsom) in SharePoint Online/2013/2016.

Example-14: Update file content using JavaScript object model (jsom) in SharePoint

Now, we will see how to update file content using the JavaScript object model (jsom) in SharePoint Online or SharePoint 2013/2016.

Here let us take a textbox where the user can enter a file name, and a multiline textbox where the user can enter the content and a submit button. On click of the submit button, the content will be updated in the file name given in the textbox.

Here as usual like other examples, we will write the code inside a script editor web part which we will put inside a web part page.

HTML Code:

<div id="UpdateFile">
<div>
<strong>Document Title to Update</strong>
<br />
<input type="text" id="txtDocumentTitle" />
</div>
<div>
<strong>Enter Update Document Content:</strong>
<br />
<textarea cols="20″ id="txtDocumentContent"></textarea>
</div>
<br />
<input type="button" id="btnSubmit" value="Update Document Content" />
</div>
<div id="divResults"></div>

Jsom Code:

Below is the jsom code to update the file content jsom in SharePoint.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
createDocument();
});
}

function createDocument() {
var docTitle = $("#txtDocumentTitle").val() + ".txt";
var docContent = $("#txtDocumentContent").val();
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
var oList = oWebsite.get_lists().getByTitle("Documents");
var fileCreateInfo = new SP.FileCreationInformation();
fileCreateInfo.set_url(docTitle);
fileCreateInfo.set_content(new SP.Base64EncodedByteArray());
for (var i = 0; i < docContent.length; i++) {
fileCreateInfo.get_content().append(docContent.charCodeAt(i));
fileCreateInfo.set_overwrite(true);
}

this.newFile = oList.get_rootFolder().get_files().add(fileCreateInfo);
clientContext.load(this.newFile);
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
$("#divResults").html("Document updated successfully!");
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() +'\n' + args.get_stackTrace());
}
</script>

Once you save the page, you can see the form below, where user can give the name of the file and then the content to update. Once the user clicks on the Update Document Content button, the document will get updated.

update file content using javascript in sharepoint
sharepoint update file programmatically

Now if you will open the document library and see the file content, you can see the updated content.

update file content using jsom in sharepoint
sharepoint update file programmatically

This is how we can update file content in SharePoint using the JavaScript object model (jsom).

Example-15: Delete file from document library using JavaScript object model (jsom) in SharePoint

Now, we will discuss how to delete a file from a SharePoint document library using a JavaScript object model (jsom). The same jsom SharePoint code we can use to delete a file from the document library in SharePoint Online as well as SharePoint 2013/2016.

Here in this example let us take an input textbox and a button, where the user can put the file name to delete and click on the Delete File button to delete the file from the SharePoint document library.

Here we will put the JavaScript and the HTML code inside a script editor web part which we will put inside a web part page. And in this example, we are searching for the file inside the Documents document library.

HTML Code:

<div id="DeleteFile">
<div>
<strong>Enter File Name to Delete:</strong>
<br />
<input type="text" id="txtDocumentTitle" />
</div>
<br />
<input type="button" id="btnSubmit" value="Delete File" />
</div>
<div id="divResults"></div>

Jsom Code:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});

function bindButtonClick() {
$("#btnSubmit").on("click", function () {
deleteDocument();
});
}

function deleteDocument() {
var docTitle = $("#txtDocumentTitle").val() + ".txt";
var clientContext = new SP.ClientContext();
var oWebsite = clientContext.get_web();
var fileUrl = _spPageContextInfo.webServerRelativeUrl + "/Shared Documents/" + docTitle;
this.fileToDelete = oWebsite.getFileByServerRelativeUrl(fileUrl);
this.fileToDelete.deleteObject();
clientContext.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),Function.createDelegate(this, this.onQueryFailed)
);
}

function onQuerySucceeded() {
$("#divResults").html("Document successfully deleted!");
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>

Once you Save the code, you can see a page like the below where the user can give the file name and then click on the button on successful deletion it will display a message like below:

delete file from document library using jsom sharepoint
sharepoint delete file programmatically

After this, if you will go to the SharePoint document library, you can not find the document because it has been already deleted.

delete file from sharepoint document library using jsom
sharepoint delete file programmatically

This is, how to delete a file from a document library using the JavaScript object model (jsom) in SharePoint.

Example-16: get sharepoint site URL programmatically using jsom

Let us see, how to get sharepoint site URL programmatically using jsom.

Now, we will see how to get SharePoint site URL using JSOM (JavaScript object model) in SharePoint Online or SharePoint 2013/2016.

Below JSOM code you can add inside a script editor web part or content editor web part in a SharePoint web part page.

<script language="javascript" type="text/javascript">
var client context;
var website;
// Make sure the SharePoint script file 'sp.js' is loaded before your
code runs.
SP.SOD.executeFunc('sp.js', 'SP.ClientContext', getWebSiteURL);
// Create an instance of the current context.
function getWebSiteURL() {
clientContext = SP.ClientContext.get_current();
website = clientContext.get_web();
clientContext.load(website);
clientContext.executeQueryAsync(onRequestSucceeded, onRequestFailed);
}
function onRequestSucceeded()
{
alert(website.get_url());
}
function onRequestFailed(sender, args)
{
alert('Error: ' + args.get_message());
}
</script>

By using the above code, we can get sharepoint site url programmatically using the JavaScript object model.

Example-17: Get selected item id from SharePoint 2013 list view using JSOM

Let us see, how to get selected item IDs from a SharePoint 2013 list view by using the JavaScript object model (jsom). Here I have a SharePoint 2013 list which has a few items. Now in the All Items view I want to know on a button click what are items selected, basically I want to get the ids of the items.

Here I have taken a button and on the button click, we are retrieving the selected list item id from SharePoint list view using javascript.

Open your SharePoint 2013 site in the browser then open the list (All Items view). Then edit the page and click on Add a web part to add a web part. Then from the Media and Content select a Script Editor web part to the page. Then put the below code inside the script editor web part.

<input type='button' value='Get Item IDs' onclick="clickMethod();"/>

<br />
<script language="javascript" type="text/javascript">
function clickMethod() {
var ctx = SP.ClientContext.get_current();
var items = SP.ListOperation.Selection.getSelectedItems(ctx);
var mySeletedItems = '';
var i;
for (i in items)
{
mySeletedItems += '|' + items[i].id;
}
alert (mySeletedItems);
}
</script>

Now Save the page and select few items from the list and then click on the button, it will display you id’s of the selected items in a dialog box as shown in the fig below:

Get selected item id from SharePoint 2013 list view using  javascript
Get selected item id from SharePoint 2013 list view using javascript

This is how to get selected item id from SharePoint 2013 list view using JSOM (JavaScript object model).

Example-18: How to set lookup column value in SharePoint using jsom

Let us see, how to set lookup column value in SharePoint 2013/2016 using jsom.

As part of my code to add /update the list items, I was trying to set the value for a lookup field using ECMA script block. When I try to do it I got the error message: fnFailedAdd. Message: Invalid data has been used to update the list item. The field you are trying to update may be read-only.

set lookup column value in SharePoint 2013
set lookup column value in SharePoint 2013

I was trying to set the lookup value with the below code:

var objCrrItem = ObjLstEnum.get_current();
objCrrItem.set_item("CompanyName", "Honda");

Note: This works for a normal field but this field is Lookup Field

JSOM code to set lookup column value sharepoint 2013

We must have to set the lookup field value with SP.FieldLookupValue() object.

The code snippet will be like as below:

var _objLkpField = new SP.FieldLookupValue();
_objLkpField.set_lookupId(1);
objCrrItem.set_item('CompanyName', _objLkpField);
The complete code will be like as below:
function fnSetlkpValue()
{
    var objClntContext = new SP.ClientContext.get_current();
    var objWeb = objClntContext.get_web();
    var ObjLst = objWeb.get_lists().getByTitle("Car Inventory");
    var camlQuery = new SP.CamlQuery();
    camlQuery.set_viewXml('<View><Query><Where><Eq><FieldRef Name=\'ID\'/><Value Type=\'Number\'>3</Value></Eq></Where></Query><RowLimit>10</RowLimit></View>');
    this.allItems =ObjLst.getItems(camlQuery);
    objClntContext.load(allItems, "Include(Title,CompanyName)");
    objClntContext.executeQueryAsync(Function.createDelegate(this, this.fnSccSetVal), Function.createDelegate(this, this.fnFailSetVal));
}
function fnSccSetVal() {
    var objClntContext = new SP.ClientContext.get_current();
    var ObjLstEnum = this.allItems.getEnumerator();
    while(ObjLstEnum.moveNext())
    {
        var objCrrItem = ObjLstEnum.get_current();
        var _objLkpField = new SP.FieldLookupValue();
        _objLkpField.set_lookupId(2); /* Updated with some lookup ID value from Primary List for lookup field */
        objCrrItem.set_item('CompanyName', _objLkpField);
        objCrrItem.update();
        objClntContext.load(objCrrItem);
        objClntContext.executeQueryAsync(Function.createDelegate(this, this.fnsuccessAdd), Function.createDelegate(this, this.fnFailedAdd));
    }
}
function fnFailSetVal(sender, args) {
    alert("fnFailSetVal. Message:" + args.get_message());
}
function fnsuccessAdd()
{
    alert("Lookup Value added Successfully!!!")
}
function fnFailedAdd(sender, args) {
    alert("fnFailedAdd. Message:" + args.get_message());
}

Little background/prerequisites to execute this script:

  • Create 2 lists
  • Primary List
  • Car Inventory
  • Create lookup field from car inventory list to primary list

With this code operation was completed successfully.

set lookup column value in SharePoint 2016
set lookup column value in SharePoint 2016
set lookup column value in SharePoint 2013 ecma script
set lookup column value in SharePoint 2013 ecma script
set lookup column value in SharePoint online
set lookup column value in SharePoint online

This is how to set lookup column value in SharePoint 2013/2016/2019 using jsom

Example-19: SharePoint list column operations using jsom

Title:
This is the default file that will get created as soon as we create a SharePoint list with the Item content type. To read the Title field

Syn:
To read value: ObjListItem.get_item(‘Title’)
To set value: ObjListItem.set_item(‘Title’, “Title Value”);

ID:
The default column get creates with the list and it is an auto-incremental field.

Syn:
To get ID: ObjListItem.get_id()

URL/Hyperlink Field: In SharePoint, URL field will have to set 2 values 1 is URL and the other one is a description.

Syn:
To get URL value – ObjListItem.get_item(‘urlfieldname’).get_url()
To set URL value – ObjListItem.set_item(‘urlfieldname’,”URL field Value”)
To get description value – ObjListItem.get_item(‘descriptionfieldname’).get_description();
To set description value – ObjListItem.set_item(“descriptionfieldname”,”description Value”);

Setting Hyperlink Field from UI:
Below is the way you can set hyperlink field through UI in SharePoint 2013.

sharepoint ecmascript

Hyperlink list field:

ecmascript sharepoint

Version Details:
To get the version details of a SharePoint list item.

Syn:
To read the version details: ObjListItem.get_item(“_UIVersionString”)

Choice field:
In SharePoint, we have a field to facilitate selecting a single value from a list of values.

Syn:
To get the value: ObjListItem.get_item(‘ChoiceFieldName’)
To set the value: ObjListItem.set_item(‘ChoiceFieldName’,’Choice Value’)

ecmascript sharepoint 2013 examples

Created Date:
SharePoint creates the default time stamp as soon as list item get created.

Syn:
To get the time stamp: objListItem.get_item(“Created”)

Modified Date:
SharePoint also tracks updated date time.

Syn:
To get the updated timestamp: objListItem. get_item(“Modified”)

Created User Name:
As we learned just before SharePoint keep track of all the operations and user accounts operated with. This will get the Created User Name.

Syn:
To get the created User Name: objListItem.get_item(“Author”).get_lookupValue()

Modified User Name:
Now that we learned to get the created user, the below will get the modified user name.

Syn:
Modified User Name: objListItem.get_item(“Editor”).get_lookupValue()

List Item Content Type:
As we learned at the beginning of the article list will get associate with one content type. If we need to know the content type associated with the list item.

Syn:
To know the Content Type: objListItem.get_contentType()

The above are a few examples of how to work with SharePoint list columns using jsom.

Example-20: How to get count of items in sharepoint list using javascript

Let us see, how to get count of items in sharepoint list using javascript.

We can also retrieve list item count using jsom (javascript client object model) in SharePoint. Put the below code inside a script editor web part or content editor web part.

<script type="text/javascript">
var clientContext = null;
var web = null;
ExecuteOrDelayUntilScriptLoaded(Initialize, "sp.js");
function Initialize()
{
clientContext = new SP.ClientContext.get_current();
web = clientContext.get_web();
var list = web.get_lists().getByTitle("MyTestList");
var camlQuery = new SP.CamlQuery();
var q = "<View><Query><Where><Eq><FieldRef Name=’Title’ /><Value Type=’Text’>abc</Value></Eq></Where></Query><RowLimit>0</RowLimit></View>";
camlQuery.set_viewXml(q);
this.listItems = list.getItems(camlQuery);
clientContext.load(listItems, ‘Include(Title)’);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onListItemsLoadSuccess),
Function.createDelegate(this, this.onQueryFailed));
}
function onListItemsLoadSuccess(sender, args) {
var count = this.listItems.get_count();
alert(count);
}

function onQueryFailed(sender, args) {
alert(‘request failed ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}
</script>

This is an example of how to get count of items in sharepoint list using javascript.

Example-21: Get internal name of SharePoint list programmatically

Let us see, how to get the internal name of the sharepoint list programmatically.

Let us see, how to get internal names of fields from list using JSOM (JavaScript object model) in SharePoint 2013/2016/2019 or SharePoint Online.

Every SharePoint list column has an internal name as well as the display name. You can change the display name but you can not change the internal name once the column got created in SharePoint Online or SharePoint 2013/2016/2019.

Below is the JSOM code which will retrieve the internal names of fields from the list using the JavaScript Object Model (jsom) in SharePoint.

You can add the below code inside a script editor web part or inside a content editor web part in SharePoint Online or SharePoint 2013/2016.

<input type="text" id="txtListTime"></input>
<input type='button' value='Get column names' onclick="GetFieldList();"/>

<script language="javascript" type="text/javascript">

function GetFieldList()
{
var listname = document.getElementById('txtListTime').value;
var ctx = SP.ClientContext.get_current();
this.web = ctx.get_web();
ctx.load(this.web);
this.list = web.get_lists().getByTitle(listname);
ctx.load(this.list);
this.fields = this.list.get_fields();
ctx.load(this.fields);
ctx.executeQueryAsync(Function.createDelegate(this, this.getListInfoSuccess), Function.createDelegate(this, this.getListInfoFail));
}

function getListInfoSuccess(sender, args)
{
var fieldEnumerator = this.fields.getEnumerator();
var results="";
while (fieldEnumerator.moveNext()) {
var oField = fieldEnumerator.get_current();
if (!oField.get_hidden())
results+= oField.get_title()
+ " – " + oField.get_internalName()
+ " – " + oField.get_hidden()
+ "\n";
}
alert(results);
}
function getListInfoFail(sender, args)
{
alert('Something failed. Error:'+args.get_message());
}
</script>

Once you Save the above code and click on the button, it will display all the internal names of the fields of SharePoint list using JavaScript. You can see the result below:

get internal name of sharepoint list programmatically
Get internal names of field from list using jsom sharepoint

This is how to get the internal name of the sharepoint list programmatically using jsom.

Example-22: Get sharepoint list items between created date using jsom

Let us see, how to get sharepoint list items between created date using jsom.

Let us see, how to retrieve list items from a SharePoint list item between a specified date range (created date).

Get SharePoint list items between created dates using JavaScript object model

In this particular example, I have used two date pickers for users to select the start date and end date. And also we will use a Script editor web part to write our javascript object model code which I have added to a SharePoint web part page.

Below is the full code to get SharePoint list items between created dates using the JavaScript object model (jsom).

<link rel="stylesheet" href="https://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="https://code.jquery.com/jquery-1.8.3.js"></script>
<script src="https://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

<script>
$(document).ready(function() {
if($("#fromdatepicker").hasClass("hasDatepicker")){
$("#fromdatepicker").removeClass("hasDatepicker")
}
if($("#todatepicker").hasClass("hasDatepicker")){
$("#todatepicker").removeClass("hasDatepicker")
}
$("#fromdatepicker").datepicker();
$("#todatepicker").datepicker();
});
</script>
From Date: <input type="text" id="fromdatepicker" />
To Date: <input type="text" id="todatepicker" />
<input type=’button’ value=’Export Data to Excel’ onclick="retrieveListItems();"/>

<script language="javascript" type="text/javascript">
function retrieveListItems() {

var query;
var startDate = $("#fromdatepicker").datepicker("getDate");
var endDate = $("#todatepicker").datepicker("getDate");
if(startDate==null)
{
alert('Please select Start Date.’);
return;
}
if(endDate==null)
{
alert('Please select End Date.’);
return;
}
if(startDate !=null && endDate !=null)
{
startDate = startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate()+’T00:00:01Z’;
endDate = endDate.getFullYear()+"-"+(endDate.getMonth()+1)+"-"+endDate.getDate()+’T00:00:01Z’;

query = "<View Scope=’RecursiveAll’><Query><Where><And><Geq><FieldRef Name=’Created’/><Value Type=’DateTime’ IncludeTimeValue=’FALSE’>"+startDate+ "</Value></Geq><Leq><FieldRef Name=’Created’/><Value Type=’DateTime’ IncludeTimeValue=’FALSE’>"+ endDate + "</Value></Leq></And></Where></Query></View>";
}
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('MyTestList’);
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(query);
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem, 'Include(Title,FirstName,LastName)’);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)); }

function onQuerySucceeded(sender, args) {
var listItemInfo = ";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext())
{
var oListItem = listItemEnumerator.get_current();
//here you can get the field values.
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n’ + args.get_stackTrace());
}
</script>

Once you save the page and select the start date and end date and click on the button it will display all the items created between the start and end date from the SharePoint list.

Get last N days record from SharePoint list using the JavaScript object model

Now, let us see how to get last N days record from SharePoint 2013 list using the JavaScript client object model.

For example, suppose we want to get the last 10 days record and we will compare with the default created date column in the SharePoint list.

The same JavaScript code, we can use to get the last N days record from SharePoint 2013/2016/Online list.

Get last N days record from SharePoint list using JavaScript

Here in this example user will put the number of days in an input textbox and click on the Submit button to display the records.

Here we will use a Script editor web part to write our code inside a SharePoint web part page.

Below is the full code to retrieve the last N days record from the SharePoint list using the JavaScript object model.

Enter number of days before: <input type='text' id='txtNumber'/> <input type='button' value='Export Data to Excel' onclick="retrieveListItems();"/>
<br />
<br />
<script language="javascript" type="text/javascript">
function retrieveListItems() {

var d = new Date();
var yyyy = d.getFullYear();
var mm = (d.getMonth()+1);
var dd = d.getDate();
var enddate=yyyy+'-'+mm+'-'+dd+'T00:00:01Z';

var nd=document.getElementById('txtNumber').value;
if(nd==")
{
nd=1;
}
var date = new Date();
var result = new Date(date);
result.setDate(date.getDate() – nd);

var yyyy = result.getFullYear();
var mm = (result.getMonth()+1);
var dd = result.getDate();
var startdate=yyyy+'-'+mm+'-'+dd+'T00:00:01Z';

var query = "<View Scope='RecursiveAll'><Query><Where><And><Geq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>"+startdate+
"</Value></Geq><Leq><FieldRef Name='Created'/><Value Type='DateTime' IncludeTimeValue='FALSE'>"+ enddate + "</Value></Leq></And></Where></Query></View>";

var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('MyTestList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(query);
this.collListItem = oList.getItems(camlQuery);

clientContext.load(collListItem, 'Include(Title,FirstName,LastName)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)); }

function onQuerySucceeded(sender, args) {
var listItemInfo = ";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext())
{
var oListItem = listItemEnumerator.get_current();
//here you can get the field values.
}
}
function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

This way we can able to get the last N days record from the SharePoint list using the JavaScript object model (jsom) in SharePoint 2013/2016 or SharePoint Online.

This is how to get SharePoint list items between created dates using the JavaScript object model (jsom) in SharePoint Online or SharePoint 2013/2016/2019.

Example-23: Export sharepoint list to excel programmatically using JavaScript

Let us see, how to export sharepoint list data to excel programmatically using JavaScript object model (jsom) and SPServices in SharePoint Online or SharePoint 2013/2016.

Recently we got one requirement to export selected list items to excel in SharePoint 2013. By default, the export to excel will export all the records from the list view.

But here the requirement was a bit different, we need only selected items to export. Due to some restrictions, we can not use any server-side code, we can use only a client-side object model code like JavaScript client object model or jQuery object model, etc.

Export sharepoint list data to excel programmatically using JavaScript and SPServices

In the list view page, we have added an HTML button and when a user clicks on that, we are exporting. Here we have used jQuery and SPServices for this purpose.

You can put the below code in the list view page inside a script editor web part.

<script type="text/javascript" src="https://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js"></script>

<div>
<input type='button' id='btbdiv' value='Generate Excel' onclick="DownloadListItems();"/>
</div>
<script language="javascript" type="text/javascript">
var projectItem1,projectItem,id;
function DownloadListItems()
{
var item;
i=0;
var table = document.getElementById('cntryTable');
while (table.rows.length > 1) {
table.deleteRow(1);
}

var context = SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
var list = context.get_web().get_lists().getByTitle("TestList");
for (item in selectedItems){
projectItem1 = selectedItems[item].id;
var CamlQuery = "<Query><Where><Eq><FieldRef Name='ID'/><Value Type='Number'>" + projectItem1 + "</Value></Eq></Where></Query>";
$().SPServices({
operation: "GetListItems",
async: false,
listName: "TestList",
CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='First_x0020_Name' /></ViewFields>",
CAMLQuery: CamlQuery,
completefunc: function (xData, Status) {

$(xData.responseXML).SPFilterNode("z:row").each(function() {
var table = document.getElementById('cntryTable');
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML =$(this).attr("ows_Title");
cell2.innerHTML =$(this).attr("ows_First_x0020_Name");
});
}
});

}
generateexcel();

}

</script>

<table id="cntryTable" border="1″ style="display:none;">
<tbody>
<tr width='250px'>
<th>Title</th>
<th>First Name</th>
</tr>
</tbody>
</table>
<br/>

<script language="javascript" type="text/javascript">
function generateexcel() {
var x = document.getElementById('cntryTable').rows;
var xls = new ActiveXObject("Excel.Application");
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.cells(i + 1, j + 1).value = y[j].innerText;
}
}

}
</script>

Save this code and when you click on the button, it should appear like below:

export sharepoint list data to excel programmatically
export sharepoint list to excel programmatically

If you want to retrieve individual records in different sheet then you can modify the generateexcel() method like the below:

<script language="javascript" type="text/javascript">
function generateexcel() {
var x = document.getElementById('cntryTable').rows;
var xls = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");

for (i = 0; i < x.length; i++) {
//xls.Workbooks.Add(z);
ExcelSheet.sheets.Add;

ExcelSheet.Application.Visible=true;
var y = x[i].cells;

var z=x[0].cells;

for (j = 0; j < y.length; j++) {
// xls.cells(i + 1, j + 1).value = y[j].innerText;
ExcelSheet.ActiveSheet.cells(1, j+1).value = z[j].innerText;
ExcelSheet.ActiveSheet.cells(2, j + 1).value = y[j].innerText;
}

}
xls.visible = true
}

</script>

This is how we can export selected records to Excel in SharePoint 2013 using the JavaScript client object model and SPServices.

Export selected record to Excel in SharePoint 2013 using JavaScript client object model

Here we got one requirement to export selected list items to Excel in SharePoint 2013 JavaScript client object model. We can not use the default export to Excel because it will export all the list view items.

we have used jQuery to export which works in Asynchronous mode. Put the below code in a script editor web part in the list view page.

<script type="text/javascript" src="https://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery.SPServices/2014.02/jquery.SPServices.min.js"></script>

<input type='button' id='btbdiv1′ value='Generate Excel' onclick="GetProjectenGoedkeuren();"/>
</div>
<script language="javascript" type="text/javascript">
var projectItem1, projectItem2, projectItem3;
var field2, field1;
var countrvalue,i,id;
var tempctx, tempItem, fieldCollection, tempList;

function GetProjectenGoedkeuren()
{
var table = document.getElementById('cntryTable');
while (table.rows.length > 1) {
table.deleteRow(1);
}

var item;
i=0;
var qryString;

var context = SP.ClientContext.get_current();
var selectedItems = SP.ListOperation.Selection.getSelectedItems(context);
var list = context.get_web().get_lists().getByTitle("TestList");
qryString ="<View><Query><Where><In><FieldRef Name='ID' /><Values>";

for (item in selectedItems){
projectItem = list.getItemById(selectedItems[item].id);
projectItem1 = selectedItems[item].id;
qryString=qryString+"<Value Type='Text'>"+projectItem1+"</Value>";
}
qryString=qryString+"</Values></In></Where></Query></View>";
camlQuery =new SP.CamlQuery();
camlQuery.set_viewXml(qryString,'Include(Title,First_x0020_Name)');
this.objitems = list.getItems(camlQuery);
context.load(objitems);
context.executeQueryAsync(Function.createDelegate(this, this.createListItem), Function.createDelegate(this, this.onQueryFailed));
generateexcel();
}

//create a new item and load it
function createListItem(sender, args) {
var listItemEnumerator = objitems.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var table = document.getElementById('cntryTable');
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);

if(oListItem.get_item('Title'))
{
cell1.innerHTML =oListItem.get_item('Title');
}
else
{
cell1.innerHTML =";
}

if(oListItem.get_item('First_x0020_Name'))
{
cell2.innerHTML =oListItem.get_item('First_x0020_Name');
}
else
{
cell2.innerHTML =";
}
}
}

function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } </script>

<table id="cntryTable" border="1″ style="display:none;">
<tbody>
<tr width='250px'>
<th>Title</th>
<th>First Name</th>
</tr>
</tbody>
</table>
<br/>

<script language="javascript" type="text/javascript">
function generateexcel() {
var x = document.getElementById('cntryTable').rows;
var xls = new ActiveXObject("Excel.Application");
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.cells(i + 1, j + 1).value = y[j].innerText;
}
}
window.location.href="https://onlysharepoint2013.sharepoint.com/Lists/TestList/AllItems.aspx";
}
</script>

If you want to retrieve individual records in different sheet then you can modify the generateexcel() method like below:

<script language="javascript" type="text/javascript">
function generateexcel() {
var x = document.getElementById('cntryTable').rows;
var xls = new ActiveXObject("Excel.Application");
var ExcelSheet = new ActiveXObject("Excel.Sheet");

for (i = 0; i < x.length; i++) {
//xls.Workbooks.Add(z);
ExcelSheet.sheets.Add;

ExcelSheet.Application.Visible=true;
var y = x[i].cells;

var z=x[0].cells;

for (j = 0; j < y.length; j++) {
// xls.cells(i + 1, j + 1).value = y[j].innerText;
ExcelSheet.ActiveSheet.cells(1, j+1).value = z[j].innerText;
ExcelSheet.ActiveSheet.cells(2, j + 1).value = y[j].innerText;
}

}
xls.visible = true
}
</script>

This is how to export sharepoint list to excel programmatically.

Example-24: Export SharePoint list items to Excel using JavaScript

Let us see, how to export SharePoint list items to Excel using the javascript object model (jsom) in SharePoint Online or SharePoint 2013/2016/2019.

I have a list name as MyTestList, we are retrieving and displaying the list items in a table. And in another button, we are exporting list items to excel in SharePoint.

The limitation of this method is export to Excel will work in IE because it requires ActiveX.

So to do this Put the below code in a single Script editor web part in a web part page in SharePoint Online or SharePoint 2013/2016.

Below is the code to display items into the table in SharePoint:

<script language="javascript" type="text/javascript">
function retrieveListItemsInclude() {
var table = document.getElementById('cntryTable');
while (table.rows.length > 1) {
table.deleteRow(1);
}
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('MyTestList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');
this.collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem, 'Include(Title)');
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed)); }
function onQuerySucceeded(sender, args) {
var listItemInfo = ";
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var table = document.getElementById('cntryTable');
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
cell1.innerHTML = oListItem.get_item('Title');
} }
function onQueryFailed(sender, args) { alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace()); } </script>
<table id="cntryTable" border="1″>
<tbody>
<tr>
<th>
Title
</th>
</tr>
</tbody>
</table>

<input type='button' value='Display List Items' onclick="retrieveListItemsInclude();"/>

Below is the code to export the data to excel in SharePoint.

<script language="javascript" type="text/javascript">
function generateexcel() {
var x = document.getElementById('cntryTable').rows;
var xls = new ActiveXObject(“Excel.Application");
xls.visible = true
xls.Workbooks.Add
for (i = 0; i < x.length; i++) {
var y = x[i].cells;
for (j = 0; j < y.length; j++) {
xls.cells(i + 1, j + 1).value = y[j].innerText;
}
}
}
</script>
<input type='button' value='Export To Excel' onclick="generateexcel();"/>

It will display like this in the page:

sharepoint export to excel javascript
sharepoint export to excel javascript

This is how to export list items to Excel using JavaScript object model in SharePoint 2013/2016/2019 or SharePoint Online.

Example-25: Add SharePoint Online custom action

Let us discuss, how to add custom actions menu options in Site Actions in SharePoint online using JavaScript Object Model.

The menu will appear when you click on the gear icon.

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>

<input name=”ADD” id=”btnAdd” type=”submit” value=”Add new custom actions” />

<script language=”javascript” type=”text/javascript”>
$(document).ready(function () {
$(“#btnAdd”).click(function () {
AddCustomActions();
});
});
function AddCustomActions() {
var clientContext = new SP.ClientContext();
var web=clientContext.get_web();
var customActions = web.get_userCustomActions();
var newCustomActionMenu = customActions.add();
newCustomActionMenu.set_location(‘Microsoft.SharePoint.StandardMenu’);
newCustomActionMenu.set_group(‘SiteActions’);
newCustomActionMenu.set_sequence(3000);
newCustomActionMenu.set_title(‘EnjoySharePoint.com’);
newCustomActionMenu.set_description(‘Go to EnjoySharePoint.com’);
newCustomActionMenu.set_url(‘https://www.enjoysharepoint.com’);
newCustomActionMenu.update();

clientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
alert(‘New Item Added to Site Actions Menu’);
}
function onFailure(sender, args) {
alert(‘Error Occurred. ‘ + args.get_message());
}
</script>

Once you will add, it will come like below:

sharepoint online custom action
sharepoint online custom action

This is how we can add SharePoint Online custom action.

Example-26: Delete SharePoint Online custom action

Let us see, how to delete custom action menu option in the Site Actions menu in SharePoint online using JavaScript Object Model.

Below is the code which will delete custom actions menu options in SharePoint.

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js”></script>
<input name=”Delete” id=”btnDelete” type=”submit” value=”Delete custom actions” />

<script language=”javascript” type=”text/javascript”>
var customActions;
var clientContext;
$(document).ready(function () {

$(“#btnDelete”).click(function () {

DeleteCustomActions();
});
});
function DeleteCustomActions() {
clientContext = new SP.ClientContext();
var web=clientContext.get_web();
customActions = web.get_userCustomActions();
clientContext.load(web, ‘UserCustomActions’, ‘Title’);

clientContext.executeQueryAsync(Function.createDelegate(this, this.onSuccess),
Function.createDelegate(this, this.onFailure));
}
function onSuccess() {
var customActionEnumerator = customActions.getEnumerator();
while (customActionEnumerator.moveNext())
{
var oUserCustomAction = customActionEnumerator.get_current();
alert(oUserCustomAction.get_title());
if (oUserCustomAction.get_title() == ‘EnjoySharePoint.com’)
{
oUserCustomAction.deleteObject();
clientContext.load(oUserCustomAction);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceededdelete), Function.createDelegate(this, this.onQueryFailed));
}
}
}
function onQuerySucceededdelete()
{
alert(‘Custom Actions Deleted Successfully’);
}
function onQueryFailed(sender, args) {
alert(‘Error Occurred. ‘ + args.get_message()+ ‘\n’ + args.get_stackTrace());
}
function onFailure(sender, args) {
alert(‘Error Occurred. ‘ + args.get_message());
}
</script>

You can see like below the menu will be removed.

sharepoint site actions
sharepoint site actions

This is how we can delete SharePoint site actions.

Example-27: Add value to SharePoint lookup field using JSOM

Let us see how to add value to the SharePoint lookup field using JSOM.

Here I have a SharePoint list that has a lookup column. That lookup column is pulling data from a SharePoint list. And I want to add an item to the list using the JavaScript object model (jsom).

So if your list lookup column allows only single value selection then you can add the lookup value like below:

Add value to SharePoint lookup field (single value selection)

var countryvalue = new SP.FieldLookupValue();
countryvalue.set_lookupId(1);
listItem.set_item('MyCountry', countryvalue);

Here 1 is the id of the source list and MyCounty is the column name of my parent list which is the lookup column name.

Below is the full code which you can put inside a Script editor web part.

<input type='button' id='1234' value='Click Me' onclick="additemstolist();"/>

<script language="javascript" type="text/javascript">

function additemstolist()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('MyTest');
var listItemInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(listItemInfo);
listItem.set_item('Title', 'My Test Title');
var countryvalue = new SP.FieldLookupValue();
countryvalue.set_lookupId(1);
listItem.set_item('MyCountry', countryvalue);
listItem.update();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailure));
}

function onSuccess() {
alert(“Item Added Successfully.");
}

function onFailure() {
alert(“Error Occured!!!");
}
</script>

Add value to SharePoint lookup field (multiple selections)

If your list lookup column allows multiple selections then you can add multiple values like below:

var lookupsIds = [1,2,3];
var lookups = [];
for (var ii in lookupsIds) {
var lookupValue = new SP.FieldLookupValue();
lookupValue.set_lookupId(lookupsIds[ii]);
lookups.push(lookupValue);
}
listItem.set_item('MyCountry', lookups);

Here in this line var lookupsIds = [1,2,3]; 1,2,3 are the id of the source list. Here suppose you want to select 2 values you can like var lookupsIds = [2,3];

Below is the full code which you can put inside a script editor web part in the web part page in SharePoint.

<input type='button' id='1234' value='Click Me' onclick="additemstolist();"/>

<script language="javascript" type="text/javascript">

function additemstolist()
{

var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle('MyTest');

var listItemInfo = new SP.ListItemCreationInformation();
var listItem = list.addItem(listItemInfo);

listItem.set_item('Title', 'My Test Title');

var lookupsIds = [1,2,3];
var lookups = [];
for (var ii in lookupsIds) {
var lookupValue = new SP.FieldLookupValue();
lookupValue.set_lookupId(lookupsIds[ii]);
lookups.push(lookupValue);
}
listItem.set_item('MyCountry', lookups);
listItem.update();
context.executeQueryAsync(Function.createDelegate(this, this.onSuccess), Function.createDelegate(this, this.onFailure));
}

function onSuccess() {
alert(“Item Added Successfully.");
}

function onFailure() {
alert(“Error Occured!!!");
}
</script>

This is how to add value to a lookup field using JavaScript Object Model in SharePoint 2013/2016/2019 and SharePoint Online.

Example-28: Cascading drop down list in SharePoint 2013 using jquery

Now, we will see how to do cascading dropdown in sharepoint using jquery and javascript.

Here we have a requirement where we have two SharePoint lists as Country and State list. There will be multiple states under a country, so the State list contains a lookup column as a country.

Two dropdown list I have created in HTML form. Now we have to bind the SharePoint country list to a drop-down on page load, and when the country is selected it should only populate corresponding states. We need to cascade country dropdown to state dropdown.

Here we have created a SharePoint custom list and a column as CountryNames.

Now we need to create a SharePoint list as State List with a lookup column as a country and have used the default Title column to enter a state.

Now we need to bind the list items to a dropdown list. For this we need to create two HTML drop-down lists.

HTML Code:

Here we have taken two drop-down lists. We have not added an option to the dropdownlist, because we will bind the dropdown list at run time from the respective SharePoint lists which we have created. We also need to pass JSOM reference and JQuery file reference. Check the below code

<!DOCTYPE HTML>
<HTML>
<head>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://onlysharepoint2013.sharepoint.com/sites/Raju/SiteAssets/Bihusdevelopment2/CountryAndStates.js"></script>
</head>
<body id="body">
Countries<select id="ddlcountry">
</select><br>
States<select id="ddlstate">
</select>
</body>
</html>

Bind Dropdownlist from SharePoint list using jQuery

We have now two dropdown list one is country other is states. Country needs to bind on page load. So to bind the country list we have created the below method.

var CountrycollListItem;

function retrieveListItems() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('CountryList');
var camlQuery = new SP.CamlQuery();
CountrycollListItem = oList.getItems(camlQuery);
clientContext.load(CountrycollListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
var listItemEnumerator = CountrycollListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
$("#ddlcountry").append('<option>' + oListItem.get_item('Title') + '</option>');
}
}
function onQueryFailed(sender, args) {
alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

Now we need to bind State list. To bind State List we need CAML query to retrieve particular states names when we choose Country name from the dropdown list.

We have created the below method and the method is called after the country method is called.

var statecollListItem;
function retriveStatelist() {
var countryname= $("#ddlcountry option:selected").text();
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('StateList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Country' /><Value Type='Lookup'>"+countryname+"</Value></Eq></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Country' /></ViewFields><QueryOptions /></View>");
statecollListItem = oList.getItems(camlQuery);
clientContext.load(statecollListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryStateSucceeded),
Function.createDelegate(this, this.onStateQueryFailed));
}

function onQueryStateSucceeded(sender, args) {
var listItemEnumerator = statecollListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
$("#ddlstate").append('<option>' + oListItem.get_item('Title') + '</option>');
}
}
function onStateQueryFailed(sender, args) {
alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

.empty(): The method is used to remove elements without destroying their data or event handlers. Multiple state values appear as when we select different countries, so if we will not execute this method we will find multiple state names in the dropdown.

Below is the complete JSOM code to display country drop down and when a country is selected shows the corresponding states.

$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
$('#ddlcountry').change(function() {
retriveStatelist();
$('#ddlstate').empty();
});
});
var CountrycollListItem;
function retrieveListItems() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('CountryList');
var camlQuery = new SP.CamlQuery();
CountrycollListItem = oList.getItems(camlQuery);
clientContext.load(CountrycollListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
var listItemEnumerator = CountrycollListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
$("#ddlcountry").append('<option>' + oListItem.get_item('Title') + '</option>');
}
}
function onQueryFailed(sender, args) {
alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}
var statecollListItem;
function retriveStatelist() {
var countryname= $("#ddlcountry option:selected").text();
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('StateList');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml("<View><Query><Where><Eq><FieldRef Name='Country' /><Value Type='Lookup'>"+countryname+"</Value></Eq></Where></Query><ViewFields><FieldRef Name='Title' /><FieldRef Name='Country' /></ViewFields><QueryOptions /></View>");
statecollListItem = oList.getItems(camlQuery);
clientContext.load(statecollListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryStateSucceeded),
Function.createDelegate(this, this.onStateQueryFailed));
}

function onQueryStateSucceeded(sender, args) {
var listItemEnumerator = statecollListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
$("#ddlstate").append('<option>' + oListItem.get_item('Title') + '</option>');
}
}
function onStateQueryFailed(sender, args) {
alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

This is how we can implement a sharepoint online cascading dropdown or sharepoint 2013 cascading dropdown using jquery.

Here, we learned how to bind sharepoint list items to dropdownlist using javascript and jQuery. We also saw how to bind cascading dropdown in sharepoint using javascript or jQuery.

Example-29: Bind SharePoint list items to dropdownlist using JavaScript

Here we have taken a SharePoint list with country names that we need to bind to a drop-down list in a web part page in SharePoint Online.

Here, I have also created an HTML file where added all the jQuery files. In this Html file, we have created a Dropdown list and have not added an option to the drop-down list, because we will bind the dropdown list at runtime using JSOM (JavaScript object model).

Here I have created a SharePoint list, name as DemoList. It has one column as Country and also I have inserted a few items to the SharePoint list.

HTML Code:

Below is my HTML file which is having the jQuery file references and also I have added an HTML dropdown like below:

Here, also I have given the reference to my custom .js file which contains by JavaScript code.

<!DOCTYPE HTML>
<HTML>
<head>
<script type="text/javascript" src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.3.1.min.js"></script>
<script type="text/javascript" src="https://onlysharepoint2013.sharepoint.com/sites/Raju/SiteAssets/Bihusdevelopment2/DropDownbindingfromlistonpageload.js"></script>
</head>
<body id="body">
<select id="ddlcountry">
</select>
</body>
</html>

JSOM code to bind SharePoint list items to dropdown on pageload:

Below is the full JavaScript code to bind sharepoint list items to dropdownlist using javascript.

$(document).ready(function () {
ExecuteOrDelayUntilScriptLoaded(retrieveListItems, "sp.js");
});

var collListItem;
function retrieveListItems() {
var clientContext = new SP.ClientContext.get_current();
var oList = clientContext.get_web().get_lists().getByTitle('DemoList');
var camlQuery = new SP.CamlQuery();
collListItem = oList.getItems(camlQuery);
clientContext.load(collListItem);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {
var listItemEnumerator = collListItem.getEnumerator();
while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
$("#ddlcountry").append('<option>' + oListItem.get_item('Title') + '</option>')
}
}

function onQueryFailed(sender, args) {
alert('Error: ' + args.get_message() + '\n' + args.get_stackTrace());
}

Once you save the code in a content editor web part or script editor web part, you can see the dropdown list will be populated from the sharePoint list.

Example-30: Get SharePoint List Attachments using JSOM

Now, we will discuss, how to get list item attachments using the JavaScript client object model (jsom) in SharePoint 2013/2016/Online.

Whenever a user does an attachment then the attachments are stored in an attachment folder and you can view that items attachment by URL:

{SITE URL}/Lists/{LIST NAME}/Attachments/{ITEM ID}/{ATTACHED FILE}

Example: http://<servername>/lists/MyTestList/Attachments/1/MyTestDoc.docx

Below is the JavaScript code to get all attachments from the SharePoint list item using JavaScript.

<script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getWebProperties, "SP.js");
var attachmentFiles;
function getWebProperties() {
var itemId=2;
var ctx = new SP.ClientContext.get_current();
var web = ctx.get_web();
var attachmentFolder=web.getFolderByServerRelativeUrl(‘Lists/City/Attachments/’+itemId);

attachmentFiles= attachmentFolder.get_files();
ctx.load(attachmentFiles);
ctx.executeQueryAsync(Function.createDelegate(this,this.onSuccess),Function.createDelegate(this,this.onFailed));
}
function onSuccess(sender, args) {
var i=0;
for(var file in attachmentFiles)
{
alert(attachmentFiles.itemAt(i).get_serverRelativeUrl());
i++;
}
}
function onFailed(sender, args) {
alert("Something went Wrong");
}
</script>

Here, we discussed how to get all list item attachments using jsom (JavaScript object model) in SharePoint.

Examples-31: Add current user to SharePoint group using JavaScript

Let us see, how to add the current SharePoint user to a SharePoint group using the JavaScript object model. We will also see, how to remove a user other than the logged-in user to the SharePoint group using the JavaScript object model (jsom).

Here we will see how to add the logged-in user to the SharePoint group using jsom and also we will see how to add a user (other than the logged-in user) to the SharePoint group using JavaScript in SharePoint Online or SharePoint 2013/2016.

Add user to SharePoint group using JavaScript

Below is the jsom code which we can add inside a script editor web part in a web part page in SharePoint Online.

<input type='button' value='Add User to SharePoint Group' onclick="AddUserToSharePointGroup();"/>
<br />

<script language="javascript" type="text/javascript">
var user;
var spGroup;
function AddUserToSharePointGroup() {

var clientContext = new SP.ClientContext.get_current();

var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(7);
user=clientContext.get_web().get_currentUser();
alert(user.email);
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}

function onQuerySucceeded() {
alert(‘success');
}

function onQueryFailed() {
alert(‘Request failed.');
}
</script>

Once you run the code, the logged-in user or the current user will be added to the SharePoint group using the JavaScript object model (jsom).

Examples-32: Add user other than logged-in user to SharePoint group using JavaScript object model

Now, we will see how to add a user other than the logged-in user to a SharePoint group using the JavaScript client object model (jsom).

Put the below code inside a script editor web part in a web part page in SharePoint Online or SharePoint 2013/2016.

Here we need to call the ensureUser() method to validate the user. And parameter it will take as domainname\username.

<input type='button' value='Add User to SharePoint Group' onclick="clickMethod();"/>
<br />

<script language="javascript" type="text/javascript">

var user;
var spGroup;
function clickMethod() {

var clientContext = new SP.ClientContext.get_current();

var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(2544);
//user=clientContext.get_web().get_currentUser();
user=web.ensureUser(“domain\\username");
var userCollection=spGroup.get_users();
userCollection.addUser(user);
clientContext.load(user);
clientContext.load(spGroup);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

function onQuerySucceeded() {
alert(‘success');
}

function onQueryFailed() {
alert(‘Request failed.');
}
</script>

Examples-33: Remove user from SharePoint group using JavaScript

Similarly, if you want to remove a user from a SharePoint group then we can use the remove() method which usually takes the user as the parameter.

Below is the full code to remove a user from a SharePoint group using JavaScript.

<input type='button' value='Remove User from SharePoint Group' onclick="RemoveUser();"/>
<br />

<script language="javascript" type="text/javascript">

var user;
var spGroup;
function RemoveUser() {

var clientContext = new SP.ClientContext.get_current();
var web=clientContext.get_web();
var siteGroups = clientContext.get_web().get_siteGroups();
spGroup=siteGroups.getById(2544);
//user=clientContext.get_web().get_currentUser();
user=web.ensureUser(“DomainName\\username");
var userCollection=spGroup.get_users();
userCollection.remove(user);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);

}

function onQuerySucceeded() {
alert(‘success');
}

function onQueryFailed() {
alert(‘Request failed.');
}

</script>

Here we discussed, how to add the logged-in user as well as other users to the SharePoint group using the JavaScript object model (jsom) in SharePoint 2013/2016 or SharePoint Online. We will also discuss how to remove a user from a SharePoint group using jsom.

Examples-34: Check if a user belongs to a SharePoint group using JavaScript

Let us see how to check if a user belongs to a SharePoint group or not using the JavaScript client object model (jsom). The jsom code we can use to check if a user belongs to the SharePoint group in SharePoint Online, SharePoint 2016/2013 also.

Below is the full code to check user belongs to the SharePoint group using jsom:

function isUserMemberOfSharePointGroup() {
var currentContext = new SP.ClientContext.get_current();
var currentWeb = currentContext.get_web();
var currentUser = currentContext.get_web().get_currentUser();
currentContext.load(currentUser);
var allGroups = currentWeb.get_siteGroups();
currentContext.load(allGroups);
var group = allGroups.getByName('MyTestGroup');
currentContext.load(group);
var groupUsers = group.get_users();
currentContext.load(groupUsers);
currentContext.executeQueryAsync(OnSuccess,OnFailure);
function OnSuccess(sender, args) {
var userInGroup = false;
var groupUserEnumerator = groupUsers.getEnumerator();
while (groupUserEnumerator.moveNext()) {
var groupUser = groupUserEnumerator.get_current();
if (groupUser.get_id() == currentUser.get_id()) {
userInGroup = true;
break;
}
}
alert (userInGroup);
}
function OnFailure(sender, args) {
alert('Something wrong happened !!!');
}
}

Examples-35: Check if user belongs to a SharePoint group JavaScript

Here is another example, of how to check if the current logged-in user belongs to a particular SharePoint group using the JavaScript object model.

Here I have a SharePoint group as “Team Site Owners” where I am checking if the current user belongs to the particular group or not.

I have put the below JavaScript code inside a script editor web part in the SharePoint web part page.

<input id="btnCheckUserCurrentGroup" onclick="CheckCurrentUserBelongstoGroup()" type="button" value="Check current user belongs to group" />

<script src="https://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
var userGroups;
function CheckCurrentUserBelongstoGroup()
{
var clientContext = new SP.ClientContext.get_current();
this.currentUser = clientContext.get_web().get_currentUser();
clientContext.load(this.currentUser);
userGroups = this.currentUser.get_groups();
clientContext.load(userGroups);
clientContext.executeQueryAsync(OnQuerySucceeded);

}

function OnQuerySucceeded() {
var isMember = false;
var groupsEnumerator = userGroups.getEnumerator();
while (groupsEnumerator.moveNext()) {
var group= groupsEnumerator.get_current();
if(group.get_title() == "Team Site Owners") {
isMember = true;
break;
}
}
alert(isMember);
}

function OnQueryFailed() {
alert('Error occured');
}

</script>

This is how to check if the user belongs to a SharePoint group javascript object model (jsom) in SharePoint Online/2013/2016.

Examples-36: Get all SharePoint groups using JavaScript Object Model (jsom)

Let us see, how to get all the SharePoint groups on the site using the JavaScript object model in SharePoint 2013/2016 or SharePoint Online.

Below is the code to get all SharePoint groups using jsom (Javascript Object Model) which I can put below code inside a script editor web part in a page in SharePoint.

<input type='button' value='Get All Groups' onclick="clickMethod();"/>

<br />

<script language="javascript" type="text/javascript">

var siteGroups =";
function clickMethod() {

var clientContext = new SP.ClientContext.get_current();

siteGroups = clientContext.get_web().get_siteGroups();
clientContext.load(siteGroups);
clientContext.executeQueryAsync(onQuerySucceeded, onQueryFailed);
}

function onQuerySucceeded() {

var allGroups='Group Name: Group ID ‘+'\n';
for (var i =0 ; i < siteGroups.get_count(); i++)
{
allGroups +=siteGroups.itemAt(i).get_title()+' ‘+siteGroups.itemAt(i).get_id()+'\n';
}
alert(allGroups);
}
function onQueryFailed() {

alert(‘Request failed.');
}
</script>

When you click on the button, it will display all the SharePoint groups and the group id like below:

get all sharepoint groups using jsom
get all sharepoint groups using jsom

This is how to get all SharePoint groups using the JavaScript object model (jsom).

Examples-37: Redirect to a different page after adding new list items in SharePoint

Now, we will see how to Redirect to a different page after adding new list items in SharePoint. The code will work in SharePoint Online, but the code will not work in Modern SharePoint Sites.

Below is the JavaScript code which you can add inside a script editor web part page.

<script  type="text/javascript" src="/sites/Test/Reports/Shared%20Documents/jquery-1.11.1.min.js"></script>  
  
<input type="button" value="Edit Item" id="editItem" onclick="MoveToViewPage()" />  
  
<script type="text/javascript">  
// get the item id parameter from the URL  
function urlParam (name){  
    var results = new RegExp('[\?&]' + name + '=([^&#]*)').exec(window.location.href);  
  
    return results[1] || 0;  
}  
  
function MoveToViewPage()  
{    
    window.location.href = "/sites/Test/Reports/Lists/Testing%20Environment/EditForm.aspx?ID=" + urlParam('ID') + "&Source=" + "/sites/Test/Reports/Lists/Testing%20Environment/DispForm.aspx?ID=" + urlParam('ID');  
}    
</script>

Examples-38: SharePoint list open attachments in a new tab

Now, in this section, we will decide how to open SharePoint list attachments in a new tab in SharePoint Online/2013/2016. We can Open list attachments in a new tab in the SharePoint list by using the below JavaScript code which you can add inside a script editor web part.

<script type="text/javascript" src="/sites/Test/Reports/Shared%20Documents/jquery-latest.js"></script>  
  
<script type="text/javascript">  
  
$(document).ready(function(){  
                $("table#idAttachmentsTable a").mousedown(function () {  
                var url=$(this).attr('href');  
                window.open(url);  
});  
});  
</script>  

Examples-39: Assign value to RichTextbox field using JavaScript in SharePoint 2013

Now we will see, how to assign a default value to a rich text box field using javascript in SharePoint 2013. And the form where we have the Rich text box is an InfoPath customized form.

Our InfoPath form is there inside a site page. And we have put one button ion the page and click on that button we wanted to put some default value to a rich textbox using javascript.

Once the form is customized the richtextbox becomes a <div> when you will check that in the view source. Here the id we got is from the view source of the page.

Add one script editor webpart and write the below code. Once you click on the submit then the text will appear in the Rich textbox.

<input type='button' id='123′ value='Click Me' onclick="updateListItem();"/>

<script language="javascript" type="text/javascript">
function updateListItem() {
document.getElementById(“ctl00_ctl30_g_412fea2a_5a21_4cf7_acbd_c9231e395d67_FormControl0_V1_I1_RTC8_RTI4_RT1_newRichText").innerHTML = ‘<b>Very bad day</b>';
}
</script>

This is not a great post but I just wanted to put it since I was trying to set the value by using the .Value property but .innerHTML worked for me. Just note the letter case here also.

Examples-40: How to display current date in SharePoint Page using JavaScript

Here we will discuss how to display the current date and time using javascript and jQuery on the SharePoint page. We can use JavaScript/jQuery code inside a content editor web part. If you want to show the current date and time on SharePoint 2013/2016 page, then you can embed the code inside a script editor web part.

Here we will append today’s date to the SharePoint page using jQuery like “weekday, YYYY/MM/dd”.

For this follow the below steps to display the current date in SharePoint Page using JavaScript.

Edit the SharePoint page and then Add a Content Editor Web Part like the below:

display current date in SharePoint 2010 Page

Now edit that Web Part and click on Click here to add new content.

After this On Ribbon under editing tools click on HTML after this On Ribbon under editing tools click on HTML Source under Format Text shown in fig.

How to display current date in SharePoint Page using JavaScript

After this one popup window is open, under this window add the following code.

<script src="/JS/jquery-1.3.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
function strpad00(s) {
s = s + ";
if (s.length === 1) s = '0' + s;
return s;
}

$(document).ready(function () {
var weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
var now = new Date();
var n = weekday[now.getDay()];
var currentDate = now.getFullYear() + "/" + strpad00(now.getMonth() + 1) + "/" + strpad00(now.getDate());
$('.s4-pagedescription').append("<div style='float:right'>" + n + "," + currentDate + "</div>");
});

</script>

Now Save the page and the date will appear like below:

How to display current date in SharePoint 2010 Page using JavaScript

This is how we can display today’s date in SharePoint page using JavaScript.

Examples-41: Display web part page in a modal dialog box using JavaScript in SharePoint

Let us see how to display web part page inside a dialog box using JavaScript in SharePoint Online or SharePoint 2013/2016.

Here we will use JavaScript and SP.UI.ModalDialog to display a web part page in the modal dialog box in SharePoint.

Remember the page should be a web part page, it will not work for wiki pages in SharePoint.

We can use the code inside a script editor web part or inside a content editor web part in a web part page in SharePoint.

<script type="text/javascript">
function OpenDialog(dialogUrl, dialogTitle) {
var options = {
url: dialogUrl,
title: dialogTitle
};
SP.UI.ModalDialog.showModalDialog(options);
}
</script>

<a href="#" onclick="OpenDialog('https://tsinfo.sharepoint.com/sites/TSInfoClassic/SitePages/Test.aspx','My Dialog Box');">Show Modal Dialog</a>

Now when you click on the above link the Test web part page will open as a dialog box. It will appear like the below:

Display web part page in a modal dialog box using JavaScript in SharePoint

This is how to display web part page in a modal dialog box using JavaScript in SharePoint Online or SharePoint 2013/2016.

Examples-42: Retrieve workflow id by using jsom in SharePoint online

Let us see how to retrieve workflow id from a list using JavaScript object model code (jsom) in SharePoint online. Here we have a list in our SharePoint Online site and into that list, we have attached a few list workflows. By using, the below code we are going to retrieve the id of the workflow whose name is “Archiving”.

In this particular example, I have added the below code inside a script editor web part which I have added inside a web part page.

<input type="button" id="btnSubmit" value="Get Workflow ID" /><br/>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(function () {
bindButtonClick();
});
function bindButtonClick() {
$("#btnSubmit").on("click", function () {
getWorkflowId();
});
}

function getWorkflowId() {
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function () {
SP.SOD.registerSod(‘sp.workflowservices.js’, SP.Utilities.Utility.getLayoutsPageUrl(‘sp.workflowservices.js’));
SP.SOD.executeFunc(‘sp.workflowservices.js’, "SP.WorkflowServices.WorkflowServicesManager", function () {
context = SP.ClientContext.get_current();
web = context.get_web();
workflowServicesManager = new SP.WorkflowServices.WorkflowServicesManager(context, web);

var subs = workflowServicesManager.getWorkflowSubscriptionService().enumerateSubscriptionsByList(‘4C384857-8AEF-484E-8163-FED3592E15A4’);
context.load(subs);
context.executeQueryAsync(function () {
var subEnumerator = subs.getEnumerator();
while (subEnumerator.moveNext()) {
var sub = subEnumerator.get_current();
if (sub.get_name() == ‘Archiving’) {
var templateId = ‘Workflow id: ‘+sub.get_id();
alert(templateId)
return;
}
}
},
function (sender, args) {
alert(args.get_message());
});
});
});
}
</script>

Once you Save the code and click on the button, it will display the workflow id inside an alert box like below:

Retrieve workflow id by using jsom in SharePoint online
Retrieve workflow id by using jsom in SharePoint online

This is how to retrieve workflow id by using jsom in SharePoint Online Office 365.

Examples-43: jquery get query string in SharePoint

This SharePoint jQuery tutorial explains, how to get query string values in SharePoint 2013 using JavaScript or jQuery. We can get the query string value inside the page by using JS request utility which we can put inside a SharePoint 2013 script editor inside the page.

The request is a utility that helps to get information from a URL. We can get information like File Name, Path Name & QueryString value from the URL.

var filename= JSRequest.FileName;
var pathname = JSRequest.PathName;
var parValue= JSRequest.QueryString["par1"];

To get the values like the above first we need to initialize the request like the below:

JSRequest.EnsureSetup();

Here is an example where we are trying to get the query string and other information by using JSRequest.

We put the below code in a script editor web part in NewForm.aspx (Edit the page and then click on Insert Web part and then from the Category select Script editor web part under media and content category).

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>

<SCRIPT type=text/javascript>
jQuery(document).ready(function() {
JSRequest.EnsureSetup();
var itemId = JSRequest.QueryString["Itemuid"];
alert ('Item ID: '+itemId);
var fileName = JSRequest.FileName;
alert('File Name: '+fileName);
var pathName = JSRequest.PathName;
alert ('Path Name: '+pathName);
});
</SCRIPT>

The results will appear like below:

get query string value in jquery sharepoint
get query string value in jquery sharepoint

This is how we can get query string parameters in SharePoint.

Examples-44: How to get dropdown text in jquery

Let us see, how we can get a drop-down list selected value and selected text using jQuery. I was having a requirement to get the dropdown selected text and selected value in my SharePoint online site.

Here I have put the code inside a script editor web part to get dropdown selected value using jquery in SharePoint Online.

Here I have a dropdown list that has 3 values like:

  • USA
  • UK
  • Canada

By using jQuery we will retrieve the selected value and text of the dropdown list.

Select Country
<select id="ddlCountry">
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">Canada</option>
</select>
<input type="button" id = "btnSelectDropDownValue" value="Retrieve Dropdown Value" />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSelectDropDownValue").click(function () {
var selectedText = $("#ddlCountry").find("option:selected").text();
alert (selectedText);
var selectedValue = $("#ddlCountry").val();
alert (selectedValue);
});
});
</script>

Once you click on the button it will show you the dropdown selected value and selected text in an alert box. You can see the output like below:

Get dropdown selected value and text using jquery
Get dropdown selected value and text using jquery

This code we can use to get dropdown selected value using jQuery.

Examples-45: javascript calendar picker

Date Picker in SharePoint will allow us to select a date from the calendar control. In this example, we will put an input box and whenever a user clicks on the input box, the date picker will appear and the user should be able to select a date from the date picker.

Add Date Picker in SharePoint using JavaScript

Open the SharePoint site and open the web part page. Edit the page, then Add a Script Editor web part from the Media and Content Category and place the below code. Now save the page.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

<script>
$(function() {
$( "#fromdatepicker" ).datepicker();
});
$(function() {
$("#btnSubmit").click(function() {
var startDate = $("#fromdatepicker").datepicker("getDate");
startDate = startDate.getFullYear()+"-"+(startDate.getMonth()+1)+"-"+startDate.getDate();

alert(startDate);
});
});
</script>

Select a Date: <input type="text" id="fromdatepicker"/>
<input type="button" id="btnSubmit" value="Get Date">

Now when you click on the button, it will display the date in the alert box.

calendar control in javascript
calendar control in javascript

Add date picker in SharePoint 2013 using JavaScript

Let us see, how to add a date picker in SharePoint page using the SharePoint javascript object model. Here in this post, we will see how the date validation work means like the start date should not be greater than the end date. And also End should not be less than the start date.

Write the below code using the script editor web part on a web part page in SharePoint 2013/2016/Online.

<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.0/themes/base/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.8.3.js"></script>
<script src="http://code.jquery.com/ui/1.10.0/jquery-ui.js"></script>

<script>
$(document).ready(function() {

$( "#fromdatepicker" ).datepicker({
onClose: function( selectedDate ) {
$( "#todatepicker" ).datepicker( "option", "minDate", selectedDate );
}
});

$( "#todatepicker" ).datepicker({
onClose: function( selectedDate ) {
$( "#fromdatepicker" ).datepicker( "option", "maxDate", selectedDate );
}
});

});
</script>
From Date: <input type="text" id="fromdatepicker" />
To Date: <input type="text" id="todatepicker" />
<input type=’button’ value=’Export Data to Excel’ onclick="retrieveListItems();"/>

<script language="javascript" type="text/javascript">
function retrieveListItems() {
var startDate = $("#fromdatepicker").datepicker("getDate");
var endDate = $("#todatepicker").datepicker("getDate");
alert(startDate);
alert(endDate);
}
</script>
javascript date selector
javascript date selector
javascript calendar picker
javascript calendar picker

This is an example of javascript calendar picker.

Examples-46: Create SharePoint content type using JavaScript

Let us see, how to create a content type using the JavaScript object model (jsom) in SharePoint Online Office 365 or SharePoint 2013/2016/2019.

For this particular example, I have added a script editor web part and in the script editor web part in a SharePoint web part page.

Here, I have taken a button and on button click, it will create the content type in the SharePoint site.

<script src="https://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>

<script type="text/javascript">
var contentTypeCollection;

function createContentType() {
var clientContext = new SP.ClientContext.get_current();
if (clientContext != undefined && clientContext != null) {
var web = clientContext.get_web();
this.contentTypeCollection = web.get_contentTypes();
this.contentType = contentTypeCollection.getById("0x0101");
var newContentType = new SP.ContentTypeCreationInformation();
newContentType.set_name('My Custom Content Type');
newContentType.set_description('My custom content type');
newContentType.set_parentContentType(contentType);
this.contentTypeCollection.add(newContentType);
clientContext.load(this.contentTypeCollection);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}
}

function onQuerySucceeded() {
alert("Content Type created successfully")
}

function onQueryFailed(sender, args) {
alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
</script>

<input id="btnCreateContentType" onclick="createContentType()" type="button" value="Create Content Type" />

Once you clicked on the button the content type will get created. You can see the content type from the site settings page. Go to site settings -> then click on “Site content types” which is under Web Designer Galleries. Then you can see your content type like below:

create content type using JavaScript sharepoint
create sharepoint content type using JavaScript

I hope this jsom sharepoint tutorial, helps to learn how to use jsom in SharePoint 2013/2016/Online. Also, we saw one example, how to insert an item to the SharePoint list using jsom.

  • Hi Bijay,

    I am new to SharePoint Development. Can you tell me how to make Recognization portal in Sharepoint server 2013

  • >