Wednesday, March 13, 2013

Add Fields to SharePoint 2013 List Using JSOM (ECMAScript Client Object Model)

Other Related Posts

In My previous post i described how to add a list to SharePoint. In here I'm going to  describe how to add fields to existing list.  First you need to refer same JavaScript files in your script page (SP.core.js,SP.runtime.js,SP.js

There are few approaches that you can use to add fields to existing list. But in my personal opinion i like following approach because

  • It is easy rather that use XML to add entire field
  • Intelligence are support based on field type (text, choice, user ..)
  • Code is more readable than xml
<script type="text/ecmascript">
function addFields() {

var clientContext = new SP.ClientContext.get_current();
var oWebsite = clientContext.get_web();
//Geting reference to the list
oList = clientContext.get_web().get_lists().getByTitle('CustomList');

// Get filed collection
var fldCollection = oList.get_fields();

var f1 = clientContext.castTo(
fldCollection.addFieldAsXml('<Field Type="Text" DisplayName="NewField" Name="NewField" />', true, SP.AddFieldOptions.addToDefaultContentType),
f1.set_description("sample desc");

var f2 = clientContext.castTo(
oList.get_fields().addFieldAsXml('<Field Type="Choice" DisplayName="choice" Name="fldchoice" />', true, SP.AddFieldOptions.addToDefaultContentType),
var choices = Array("Approved", "Rejected", "Progress");

Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)

function onQuerySucceeded() {
alert("List Field Updated");

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


In this example I'm adding SharePoint Choice Field (SP.FieldChoice)  and SharePoint Text Field to existing SharePoint list.

Note: You can you addFieldAsXml and can give complete xml as a string to add the field as well.

Post a Comment