Tuesday 23 October 2012

ECMAScript to Generate Sequential Number on list form

If you want to generate a sequential number in a text box of list form on page load, you can achieve this by simply adding a ECMAScript on the list form using content editor webpart.

Below is the code:

Points to Remember: 
1. Replace ColumnInternalName with the internal name of your column where you want the auto generated number.
2. YourLISTID is id of your list
3. Column Id  is id of you column get using View Source
4.  It will Generate number like Dep-1 ,Dep-2 ,Dep-3, Dep-4, Dep-5......etc
You can change dep to any string

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

var context = null;
var web = null;
var MaxID;
var FDN;

function Start()
{
context = new SP.ClientContext.get_current();
web = context.get_web();
context.load(web);
var list = web.get_lists().getById("YourLISTID");
context .load(list);
var camlQuery = new SP.CamlQuery();
Ascending="FALSE" /></OrderBy></Query><RowLimit>1</RowLimit></View>';
var str='<View><Query<OrderBy><FieldRef Name="ColumnInternalName" Ascending="FALSE" /></OrderBy></Query><RowLimit>1</RowLimit></View>';
camlQuery.set_viewXml(str);
allItems = list.getItems(camlQuery);
context.load(allItems, 'Include(ColumnInternalName)');
context.executeQueryAsync(Function.createDelegate(this, this.onSuccessMethod),Function.createDelegate(this, this.onFailureMethod));
 }
function onSuccessMethod(sender, args)
{
var ListEnumerator = this.allItems.getEnumerator();
while(ListEnumerator.moveNext())
{
var currentItem = ListEnumerator.get_current();
MaxID=currentItem.get_item('ColumnInternalName');
}
 if( MaxID==null)
{
MaxID=1;
var MyData="Dep-" + MaxID;
document.getElementById("Column Id ").value=MyData;
}
else
{
var strId=MaxID.split("-");
var data1=parseInt(strId[1])+1;
var data="Dep-" + data1;
document.getElementById("Column Id").value=data;
}
}
function onFailureMethod(sender, args)
{
alert("Hi2");
}</script>

You are Done!

No comments:

Post a Comment