SharePoint Online jsom examples (25 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.

You may like 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

  • >