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 11 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 in SharePoint Add-in.

As in most of the cases, you will not get access to deploy your server-side code, this will help you much in those scenarios. From SharePoint 2010 towards the next versions, there is a lot of improvements towards the client-side object model. Lots of classes available to work with the client-side object model.

We can access and manipulate SharePoint objects like Site, Web, List, ContentTypes, User Permission using ECMAScript client object model which works in asynchronous mode.

At A Glance - Here's what we'll cover: show

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 the 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 client made an Http request to the server, the server tries to load the page and the master page. If the page using 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.

The 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 which 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" />

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/2013/2016

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="https://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 JavaScript object model (jsom). In the same way, we can get alternative languages in SharePoint 2013/2016 using JavaScript.

If you want to retrieve alternative languages in SharePoint using Rest API, then you can follow this article.

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 into 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 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 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, and a button etc. And we will have a js file which 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 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 which 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 like 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 below where user can give the file name and then click on the button and 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 JavaScript object model.

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

Let us see, how to get selected item id’s from a SharePoint 2013 list view by using JavaScript object model (jsom). Here I have a SharePoint 2013 list which has 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 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 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 filed will get created as soon as we create a SharePoint list with Item content type. To read 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 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 internal name of 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 internal names of field from list using 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 internal name of 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 into 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 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 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 on 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 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 an 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 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 complete JSOM code to display country drop down and when a country is selected shows corrosponding 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 were 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 the 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/2013/2016.

<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 the 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/2013/2016, 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 in SharePoint page. We can use JavaScript/jQuery code inside a content editor web part. If you want show current date and time in SharePoint 2013/2016 page, then you can embed the code inside a script editor web part.

Here we will append today’s date in 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 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 the 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 then Test web part page will open as a dialog box. It will appear like 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 above first we need to initialize the request like 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="https://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 parameter in SharePoint.

Examples-44: How to get dropdown text in jquery

Let us see, how we can get 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="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>
$(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="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() {

$( "#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: Get Middle East prayer timing using JavaScript in SharePoint

I have created a simple webpart to get QATAR local paryer timing using JavaScript code in SharePoint.

Get timing using JavaScript Code in SharePoint

Step 1: Open the SharePoint Online site where you want to display the time. and then add a script editor web part into the web part page.

Step 2: Add the below JavaScript code in your project.

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>


<script>  
    var canvas;  
    var ctx;  
    var radius;  
    $(document).ready(function () {  
        canvas = document.getElementById("canvas");  
        ctx = canvas.getContext("2d");  
        radius = canvas.height / 2;  
        ctx.translate(radius, radius);  
        radius = radius * 0.90  
        setInterval(drawClock, 1000);          
    });  
  
    function drawClock() {  
        drawFace(ctx, radius);  
        drawNumbers(ctx, radius);  
        drawTime(ctx, radius);  
    }  
  
    function drawFace(ctx, radius) {  
        var grad;  
        ctx.beginPath();  
        ctx.arc(0, 0, radius, 0, 2 * Math.PI);  
        ctx.fillStyle = 'white';  
        ctx.fill();  
        grad = ctx.createRadialGradient(0, 0, radius * 0.95, 0, 0, radius * 1.05);  
        grad.addColorStop(0, '#333');  
        grad.addColorStop(0.5, 'white');  
        grad.addColorStop(1, '#333');  
        ctx.strokeStyle = grad;  
        ctx.lineWidth = radius * 0.1;  
        ctx.stroke();  
        ctx.beginPath();  
        ctx.arc(0, 0, radius * 0.1, 0, 2 * Math.PI);  
        ctx.fillStyle = '#333';  
        ctx.fill();  
    }  
  
    function drawNumbers(ctx, radius) {  
        var ang;  
        var num;  
        ctx.font = radius * 0.15 + "px arial";  
        ctx.textBaseline = "middle";  
        ctx.textAlign = "center";  
        for (num = 1; num < 13; num++) {  
            ang = num * Math.PI / 6;  
            ctx.rotate(ang);  
            ctx.translate(0, -radius * 0.85);  
            ctx.rotate(-ang);  
            ctx.fillText(num.toString(), 0, 0);  
            ctx.rotate(ang);  
            ctx.translate(0, radius * 0.85);  
            ctx.rotate(-ang);  
        }  
    }  
  
    function drawTime(ctx, radius) {  
        var now = new Date();  
        var hour = now.getHours();  
        var minute = now.getMinutes();  
        var second = now.getSeconds();  
        //hour  
        hour = hour % 12;  
        hour = (hour * Math.PI / 6) +  
            (minute * Math.PI / (6 * 60)) +  
            (second * Math.PI / (360 * 60));  
        drawHand(ctx, hour, radius * 0.5, radius * 0.07);  
        //minute  
        minute = (minute * Math.PI / 30) + (second * Math.PI / (30 * 60));  
        drawHand(ctx, minute, radius * 0.8, radius * 0.07);  
        // second  
        second = (second * Math.PI / 30);  
        drawHand(ctx, second, radius * 0.9, radius * 0.02);  
    }  
  
    function drawHand(ctx, pos, length, width) {  
        ctx.beginPath();  
        ctx.lineWidth = width;  
        ctx.lineCap = "round";  
        ctx.moveTo(0, 0);  
        ctx.rotate(pos);  
        ctx.lineTo(0, -length);  
        ctx.stroke();  
        ctx.rotate(-pos);  
    }  
</script>  
  
<script>  
  
    $(document).ready(function () {  
        var settings = {  
            "async": true,  
            "crossDomain": true,  
            "url": "https://aladhan.p.mashape.com/timingsByCity?city=Doha&country=Qatar",  
            "method": "GET",  
            "headers": {  
                "x-mashape-key": "4seB9mx5g0mshrkpLviV9IsQKRYNp1cZ9n8jsn70KjeMIgrBxm"  
            }  
        }  
  
        $.ajax(settings).done(function (response) {  
            console.log(response);  
            //var responseObj = JSON.parse(response);  
            var d = new Date();  
            var n = d.getHours();  
            var m = d.getMinutes();  
            m = m / 60;  
            n = n+m;  
            if (n < 6) {  
                $('.prayer_laber ').text("Fajr");  
                $('.prayer_timing').text(response.data.timings.Fajr);  
            }  
            else if (n < 11 && n > 6) {  
                $('.prayer_laber').text("Dhuhr");  
                $('.prayer_timing').text(response.data.timings.Dhuhr);  
            }  
            else if (n < 14 && n > 11) {  
                $('.prayer_laber').text("Asr");  
                $('.prayer_timing').text(response.data.timings.Asr);  
            }  
            else if (n < 16 && n > 14) {  
                $('.prayer_laber').text("Maghrib");  
                $('.prayer_timing').text(response.data.timings.Maghrib);  
            }  
            else if (n < 20 && n > 16) {  
                $('.prayer_laber').text("Isha");  
                $('.prayer_timing').text(response.data.timings.Isha);  
            }  
        });  
    });  
</script>  

The output will appear like below:

get middle east prayer timing JavaScript

get middle east prayer timing JavaScript

This is how to get middle east prayer timing JavaScript code.

Examples-47: JavaScript get weather

Let us see an example on javascript get weather or weather javascript code.

We can get current weather using JavaScript and display it on the SharePoint page. Here we will see how we can use OpenWeatherMap Weather API using JavaScript in SharePoint.

OpenWeatherMap is one of the leading digital weather information providers. The OpenWeatherMap API is free to use and it also has a paid version having more weather data and features.

OpenWeatherMap provides:

  • Current weather for any geolocation
  • 5-days/3 hour weather forecast
  • 16-days/daily weather forecast
  • Historical weather data for 6 years in the past
  • Weather maps: Forecast, Historical, Current
  • Relief maps
  • Weather alerts
  • UV index
  • Network of weather stations

Get current weather javascript SharePoint

To get current weather using JavaScript SharePoint, check out the OpenWeatherMap guide to generate the API key which we will use to call.

In SharePoint, we can insert the code using a Script editor web part or a content editor web part inside a web part page.

Step 1: Open you SharePoint site and Add a Script Editor Web part in your web part page.

Step 2: Add the CSS and JavaScript file as a reference.

Step 3: Copy the below code

<script src="https://gist.github.com/lyuba/874368"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.2.4.js"></script>  
<script type="text/javascript">  
    $(document).ready(function () {  
        var settings = {  
            "async": true,  
            "crossDomain": true,  
            "url": "https://api.openweathermap.org/data/2.5/weather?lat=25.2854&lon=51.5310&units=metric&appid=8419181060b4dc0a4080aca18bcd29b6",  
            "method": "GET",  
            "processData": false,  
            "contentType": false,  
            "mimeType": "multipart/form-data",  
        }  
        $.ajax(settings).done(function (response) {  
            console.log(response);  
            var data = JSON.parse(response);  
            var selector;  
            switch (data.weather[0].main) {  
                case 'Haze': $('.Windy').show(); selector = '.' + 'Windy' + '_';  
                    break;  
                case 'Cloudy': $('.Cloudy').show(); selector = '.' + data.weather[0].main + '_';  
                    break;  
                case 'Rain': $('.Rain').show(); selector = '.' + data.weather[0].main + '_';  
                    break;  
                case 'Windy': $('.Windy').show(); selector = '.' + data.weather[0].main + '_';  
                    break;  
                case 'Snow': $('.Snow').show(); selector = '.' + 'Cloudy' + '_';  
                    break;  
                case 'Mist': $('.Cloudy').show(); selector = '.' + 'Cloudy' + '_';  
                    break;  
                default: $('.Cloudy').show(); selector = '.' + data.weather[0].main + '_';  
            }  
            $(selector + 'temp').text(data.main.temp + "°");  
            $(selector + 'wind').text(data.wind.speed + "MPH");  
            $(selector + 'humidity').text(data.main.humidity + "%");  
            $(selector + 'pressure').text(data.main.pressure + "°");  
        })  
            .fail(function (response) {  
                console.log("error fecting wether data");  
  
            });  
  
    });  
</script>  
<!-- end script for weather-->

Step 4: Click on the Save button and now you will get current weather in QATAR. in the SharePoint Page.

You can check the console (In Google Chrome More tools -> Developer Tools), and the output will appear like below:

javascript get weather
javascript get weather

This is how to get current weather using JavaScript in SharePoint Online/2013/2016/2019.

Examples-48: 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

You may like the following jsom SharePoint examples:

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

  • >