Monday 17 February 2014

How to create Sharepoint List using Client Object Model (JavaScript)

How to create Sharepoint List using Client Object Model (JavaScript) ?

To Create a SP List follow the below steps :

Step 1 : Add HTML TextBox and Button fields to HTML file as below.

          <h2>List Creation</h2>
          <table >
            <tr>
               <td>
                    List Name :
               </td>
               <td>
                   <input id="tbList" type="text" />
               </td>
            </tr>
            <tr>
               <td >
                   <input type="button" id="btnCreateList" value="Create List"onclick="CreateList()" />
               </td>
            </tr>
         </table>

Step 2 : Add below Script to create a SPList when you fill Textbox and click 'OK' button.

    <script type="text/javascript">
    var siteUrl = "/";  //give your site url. Ex: sitecollectionTitle/siteTitle
    function CreateList() {
        var listName = document.getElementById("tbList");
        var clientContext = new SP.ClientContext(siteUrl);
        var oWebsite = clientContext.get_web();
        var listCreationInfo = new SP.ListCreationInformation();
        listCreationInfo.set_title(listName.value);
        listCreationInfo.set_templateType(SP.ListTemplateType.genericList);
        var oList = oWebsite.get_lists().add(listCreationInfo);
        clientContext.load(oList);
        clientContext.executeQueryAsync(Function.createDelegate(this,this.onQuerySucceeded), Function.createDelegate(thisthis.onQueryFailed));
    }
    function onQuerySucceeded() {
        alert('Request successfully completed');
    }
    function onQueryFailed(sender, args) {
        alert('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }
   </script>


Step 3 :  Execute the above code.Enter the list name in the textbox and click button. Now the list gets created.

Enjoy Coding....

No comments:

Post a Comment