SharePoint Online jsom examples

In this SharePoint tutorial, we will discuss a few 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.

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:

Retrieve alternative languages in SharePoint using JavaScript

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.

Steps to create list jsom sharepoint 2013
Steps to create list jsom sharepoint 2013

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.

Steps to create list jsom sharepoint 2016
Steps to create list jsom sharepoint 2016

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:

Steps to create list jsom sharepoint online
Steps to 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:

Steps to delete list jsom sharepoint online
Steps to 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).

You may like following jsom SharePoint examples:

Hope this SharePoint jsom 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

  • >