How to disable tabs using jQuery

Hello friends, in this article we will see how to disable tabs using jQuery.

How to disable tabs using jQuery

First, let us create a tabs structure using html and jQuery as follows:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>jQuery UI Tabs - Default functionality</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <link rel="stylesheet" href="/resources/demos/style.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script>
  $( function() {
    $( "#tabs" ).tabs();
  } );
  </script>
</head>
<body>
 
<div id="tabs">
  <ul>
    <li><a href="#tabs-1">India</a></li>
    <li><a href="#tabs-2">United States</a></li>
    <li><a href="#tabs-3">China</a></li>
  </ul>
  <div id="tabs-1">
    <p>India, also known as the Republic of India, is a country in South Asia. It is the seventh largest country by area and with more than 1.3 billion people, it is the second most populous country as well as the most populous democracy in the world.</p>
  </div>
  <div id="tabs-2">
    <p>The U.S. is a country of 50 states covering a vast swath of North America, with Alaska in the northwest and Hawaii extending the nation’s presence into the Pacific Ocean. Major Atlantic Coast cities are New York, a global finance and culture center, and capital Washington, DC. Midwestern metropolis Chicago is known for influential architecture and on the west coast, Los Angeles' Hollywood is famed for film making.</p>
  </div>
  <div id="tabs-3">
    <p>China is a populous nation in East Asia whose vast landscape encompasses grassland, desert, mountains, lakes, rivers and more than 14,000km of coastline. Capital Beijing mixes modern architecture with historic sites such as the Forbidden City palace complex and Tiananmen Square. Shanghai is a skyscraper-studded global financial center. The iconic Great Wall of China runs east-west across the country's north.</p>
  </div>
</div>
 
 
</body>
</html>

Now to disable second and third tab, we just need to modify a single line of .tabs() function in the above code as follows:

$( "#tabs" ).tabs( { disabled: [1, 2] } );

In the above line, we used the position of tabs to be disabled. (index starts with 0). This will result in the the disabled tabs as below:

disable tabs using jQuery
disabled tabs using jQuery

I hope you liked this article. If you have any queries, please use below comments section for the same. Please like our Facebook page and subscribe to our newsletter for future updates. Have a nice day! tada…

Custom Client Side People Picker in SharePoint using jQuery

Hello friends, in this tutorial we will develop a custom client side people picker control in SharePoint. It is applicable for SharePoint 2013, 2016 and SharePoint Online.

In the first section, we will save the people picker value in SharePoint list (people picker field) using REST API.

In the second section we will see, how to get the value of people picker field from SharePoint list and set to our custom people picker field, as shown below:

Section 1: Create custom people picker field and save its value in SharePoint list.

Step 1: Create a list named EmpDetails. Create a person or group field named EmployeeName. We are going to save of custom field value in this list field.

Step 2: Create a webpart page and add content editor webpart

Step 3: Add below code and we are ready with our custom field.

Download below code: Download link

<!-- Created by https://myclassbook.org/custom-client-side-people-picker-in-sharepoint-using-jquery/ -->
<html>
   <head>
      <script src="/teams/MyClassBook/CustomCode/jquery.min.js"></script> 
      <script src="/_layouts/15/sp.runtime.js"></script>  
      <script src="/_layouts/15/sp.js"></script>  
      <script src="/_layouts/15/1033/strings.js"></script>  
      <script src="/_layouts/15/clienttemplates.js"></script>  
      <script src="/_layouts/15/clientforms.js"></script>  
      <script src="/_layouts/15/clientpeoplepicker.js"></script>  
      <script src="/_layouts/15/autofill.js"></script>  
      <script src="_layouts/15/sp.core.js"></script> 
      <script>
         // Run your custom code when the DOM is ready.
         $(document).ready(function () {
         
             // Specify the unique ID of the DOM element where the
             // picker will render.
             initializePeoplePicker('peoplePickerDiv');
         });
         
         // Render and initialize the client-side People Picker.
         function initializePeoplePicker(peoplePickerElementId) {
         
             // Create a schema to store picker properties, and set the properties.
             var schema = {};
             schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
             schema['SearchPrincipalSource'] = 15;
             schema['ResolvePrincipalSource'] = 15;
             schema['AllowMultipleValues'] = true;
             schema['MaximumEntitySuggestions'] = 50;
             schema['Width'] = '280px';
         
             // Render and initialize the picker. 
             // Pass the ID of the DOM element that contains the picker, an array of initial
             // PickerEntity objects to set the picker value, and a schema that defines
             // picker properties.
             this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
         }
         
         // Query the picker for user information.
         function getUserInfo() {
         
             // Get the people picker object from the page.
             var peoplePicker = this.SPClientPeoplePicker.SPClientPeoplePickerDict.peoplePickerDiv_TopSpan;
         
             // Get information about all users.
             var users = peoplePicker.GetAllUserInfo();
             var userInfo = '';
             for (var i = 0; i < users.length; i++) {
                 var user = users[i];
                 for (var userProperty in user) { 
                     userInfo += userProperty + ':  ' + user[userProperty] + '<br>';
                 }
             }
             $('#resolvedUsers').html(userInfo);
         
             // Get user keys.
             var keys = peoplePicker.GetAllUserKeys();
             $('#userKeys').html(keys);
         
             // Get the first user's ID by using the login name.
             getUserId(users[0].Key);
         }
         
         // Get the user ID.
         function getUserId(loginName) {
             var context = new SP.ClientContext.get_current();
             this.user = context.get_web().ensureUser(loginName);
             context.load(this.user);
             context.executeQueryAsync(
                  Function.createDelegate(null, ensureUserSuccess), 
                  Function.createDelegate(null, onFail)
             );
         }
         
         function ensureUserSuccess() {
         	createitem(this.user.get_id());
             $('#userId').html(this.user.get_id());
         }
         
         function onFail(sender, args) {
             alert('Query failed. Error: ' + args.get_message());
         }   
         
         //Rest API function to create an item in a list
         function createitem(userId){
         	$.ajax({
                 url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmpDetails')/Items",
                 type: 'POST',
                 headers: {
                     "Accept": "application/json;odata=verbose",
                     "Content-Type": "application/json;odata=verbose",
                     "X-RequestDigest": $("#__REQUESTDIGEST").val(),
                     "X-HTTP-Method": "POST"
                 },
                 data: JSON.stringify({
                     __metadata: {
                         type: "SP.Data.EmpDetailsListItem"
                     },
                     Title: "Mayuresh Dinkar Joshi",            
                     EmployeeNameId: userId, //internalName is 'EmployeeName' but we have to use 'EmployeeNameId' to pass id of a person            
                 }),
                 success: function(data) {
                     alert('Item created successfully!');
                 },
                 error: function(error) {
                     alert(JSON.stringify(error));
                 }
             });
         }   
      </script>
   </head>
   <body>
      <div id="peoplePickerDiv"></div>
      <div>
         <br/>
         <input type="button" value="Get User Info and Create Item" onclick="getUserInfo()"></input>
         <br/>
         <h1>User info:</h1>
         <p id="resolvedUsers"></p>
         <h1>User keys:</h1>
         <p id="userKeys"></p>
         <h1>User ID:</h1>
         <p id="userId"></p>
      </div>
   </body>
</html>

Step 4: Our custom people picker field will look like as below:

Custom people picker field

Step 5: When we search for any name and click on button, it will populate that users details and also save the value in our custom list field which we created in step 1. See below screenshots:

Custom people picker field in sharepoint
Custom people picker field in SharePoint
Custom people picker field in SharePoint
Custom people picker field in SharePoint

Section 2: Get person field value from SharePoint list and set the value to custom people picker field.

Step 1: We have a list named EmpDetails with person or group field as EmployeeName.

Step 2: We will fetch the value for an item with ID=1 and set its value to our custom people picker field.

Step 3: Create a webpart page and add content editor webpart.

Step 4: Add below code in content editor webpart.

Note: I have passed hard-coded URL with item ID 1. I will recommend you to edit the logic accordingly to pass the ID dynamically using text field.

Download below code: Download link

<!--Created by https://myclassbook.org/custom-client-side-people-picker-in-sharepoint-using-jquery/ -->
<html>
<head>
    <script src="/teams/MyClassBook/CustomCode/jquery.min.js"></script>
    <script src="/_layouts/15/sp.runtime.js"></script>
    <script src="/_layouts/15/sp.js"></script>
    <script src="/_layouts/15/1033/strings.js"></script>
    <script src="/_layouts/15/clienttemplates.js"></script>
    <script src="/_layouts/15/clientforms.js"></script>
    <script src="/_layouts/15/clientpeoplepicker.js"></script>
    <script src="/_layouts/15/autofill.js"></script>
    <script src="_layouts/15/sp.core.js"></script>
    <script>
        // Run your custom code when the DOM is ready.
        $(document).ready(function() {
            // Specify the unique ID of the DOM element where the
            // picker will render.
            initializePeoplePicker('peoplePickerDiv');
        });
        // Render and initialize the client-side People Picker.
        function initializePeoplePicker(peoplePickerElementId) {
            // Create a schema to store picker properties, and set the properties.
            var schema = {};
            schema['PrincipalAccountType'] = 'User,DL,SecGroup,SPGroup';
            schema['SearchPrincipalSource'] = 15;
            schema['ResolvePrincipalSource'] = 15;
            schema['AllowMultipleValues'] = true;
            schema['MaximumEntitySuggestions'] = 50;
            schema['Width'] = '280px';
            // Render and initialize the picker. 
            // Pass the ID of the DOM element that contains the picker, an array of initial
            // PickerEntity objects to set the picker value, and a schema that defines
            // picker properties.
            this.SPClientPeoplePicker_InitStandaloneControlWrapper(peoplePickerElementId, null, schema);
        }
        function readItem() {
            $.ajax({
                url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists/getByTitle('EmpDetails')/Items(1)?$select=EmployeeName/EMail&$expand=EmployeeName/Id",
                type: 'GET',
                headers: {
                    "accept": "application/json;odata=verbose",
                },
                success: function(data) {
                    console.log(data.d.EmployeeName.EMail);
                    SetAndResolvePeoplePicker(data.d.EmployeeName.EMail);
                },
                error: function(error) {
                    alert(JSON.stringify(error));
                }
            });
        }
        function SetAndResolvePeoplePicker(userAccountName) {
            var _PeoplePickerEditer = $("#peoplePickerDiv_TopSpan_EditorInput");
            userAccountName.split(";#").forEach(function(part) {
                if (part !== "" && part !== null) {
                    //  alert(part);
                    _PeoplePickerEditer.val(part);
                    var _PeoplePickerOject = SPClientPeoplePicker.SPClientPeoplePickerDict["peoplePickerDiv_TopSpan"];
                    _PeoplePickerOject.AddUnresolvedUserFromEditor(true);
                }
            });
        }
    </script>
</head>
<body>
    <div id="peoplePickerDiv"></div>
    <div>
        <br />
        <input type="button" value="Set people picker" onclick="readItem()"></input>
        <br />
    </div>
</body>
</html>

Step 5: When we click on a given button, it will call a REST API to fetch the value of person field of list item of ID 1 and set its value to out custom people picker field. We can use this scenario when we need to fetch person fields in our custom edit form.

I hope you liked this article. If you have any queries, please use below comments section for the same. Please like our facebook page and subscribe to our newsletter for future updates. Have a nice day! tada…

How to Hide SharePoint Field using jQuery/JavaScript

Hello friends, in this article, we will see how we can Hide SharePoint Field in NewForm.aspx/ DispForm.aspx/ EditForm.aspx

Add a content editor webpart on respective pages (NewForm.aspx/ DispForm.aspx/ EditForm.aspx) and use below JavaScript/jQuery code to hide sharepoint field. In this case, I am hiding named “Middle Name”.

  1. For NewForm.aspx OR EditForm.aspx

    using jQuery

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $('nobr:contains("Middle Name")').closest('tr').hide(); //here we are hiding field named "Middle Name"
    });
    </script>

    using JavaScript

    <script type="text/javascript">
    
    // The new closest
    var closest = function(el, fn) {
      return el && (fn(el) ? el : closest(el.parentNode, fn));
    };
    
    // Get the "starting point" element
    var srcEl = document.getElementById('Middle_x0020_Name');
    
    // `<tr>` is the "ending point"
    var tr = closest(srcEl, function(el) {    
        return el.tagName.toLowerCase() === 'tr';
    });
    
    tr.style.display = "none";
    
    </script>
    
    
  2. For DispForm.aspx

    using jQuery

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>
    $(document).ready(function(){
    $('[name="SPBookmark_Middle_x0020_Name"]').closest('tr').hide();
    });
    </script>

    using JavaScript

    <script type="text/javascript">
    
    // The new closest
    var closest = function(el, fn) {
      return el && (fn(el) ? el : closest(el.parentNode, fn));
    };
    
    // Get the "starting point" element
    var srcEl = document.getElementsByName('SPBookmark_Middle_x0020_Name');
    srcEl;
    // `<tr>` is the "ending point"
    var tr = closest(srcEl[0], function(el) {    
        return el.tagName.toLowerCase() === 'tr';
    });
    
    tr.style.display = "none";
    
    </script>

Explanation of code:

How to hide SharePoint field using JavaScript

If you see the first code for hiding SharePoint field on New or Edit forms, we have used the closest function of jquery. We are using <nobr> tag value to find the closest <tr> tag of the field and hiding it. You can refer below screenshot to find the <nobr> value (It’s always same as field display name).

Hide SharePoint Field
Hide SharePoint Field

A similar approach is used for remaining codes. I hope you have liked this article. If you have any queries, feel free to ask in the comment section below. Like our facebook page and subscribe to our newsletter for future updates. Have a nice day!

Recommended articles:

  1. SharePoint Interview Questions
  2. SharePoint Content Types – Best Explained
  3. SharePoint Site Columns – Best Explained
  4. How to Make Conditionally Mandatory Field in SharePoint 2013

How to call one function inside second in jQuery/JavaScript

Hello friends,

In this short article, we will see, how can we call one function inside second in JavaScript.

Let’s consider you have a function named makeAddition() as follows:

function makeAddition(a,b){
   var c = a+b;
   alert("Addition: "+ c);
}

Now if you have another function named makeSubtraction() as follows:

function makeSubtraction(a,b){
   var d = a-b;
   alert ("Subtraction: "+ d);
}

You can call makeAddition function inside makeSubtraction function as follows:

function makeSubtraction(a,b){
   var d = a-b;
   alert ("Subtraction: "+ d);
   makeAddition (4,5);
}

Now when you call makeSubtraction (10,5), it will first alert answer as 5 and then it will call makeAddition function and will alert answer as 9.

You may also like:

I hope you liked this article. If you have any queries, please use below comments section for the same. Please like our facebook page and subscribe to our newsletter for future updates. Have a nice day! tada…

Convert Excel to JSON using JavaScript code

Hello friends, in this javascript tutorial we are going to learn about how to Convert Excel to JSON using JavaScript code. We can read an excel file which is hosted on any server, SharePoint folder, etc with the help of javascript code. Here you can get readymade javascript code for Excel to JSON conversion.

Excel to JSON
Excel to JSON

Convert Excel to JSON using JavaScript Code

In this tutorial, we are going to use a js-xlsx library to convert Excel to JSON. It has xlsx.full.min.js file which we are going to refer in our HTML file. js-xlsx is a parser and writer for various spreadsheet formats. So without wasting time lets jump to coding part. We can also use .csv files as well.

Below is a code for reading Excel as a JSON object:

<!doctype html>
<html>

<head>
    <title>Excel to JSON Demo</title>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.13.5/xlsx.full.min.js"></script>
</head>

<body>

    <script>
        /* set up XMLHttpRequest */
        var url = "https://myclassbook.org/wp-content/uploads/2017/12/Test.xlsx";
        var oReq = new XMLHttpRequest();
        oReq.open("GET", url, true);
        oReq.responseType = "arraybuffer";

        oReq.onload = function(e) {
            var arraybuffer = oReq.response;

            /* convert data to binary string */
            var data = new Uint8Array(arraybuffer);
            var arr = new Array();
            for (var i = 0; i != data.length; ++i) arr[i] = String.fromCharCode(data[i]);
            var bstr = arr.join("");

            /* Call XLSX */
            var workbook = XLSX.read(bstr, {
                type: "binary"
            });

            /* DO SOMETHING WITH workbook HERE */
            var first_sheet_name = workbook.SheetNames[0];
            /* Get worksheet */
            var worksheet = workbook.Sheets[first_sheet_name];
            console.log(XLSX.utils.sheet_to_json(worksheet, {
                raw: true
            }));
        }

        oReq.send();
    </script>
</body>

</html>

In the above code, if you could observe, you will find that we have used xlsx.full.min.js file and a Test.xlsx file. We are going to read Test.xlsx Excel file to generate a JSON Object.

Note: While using the above code make sure that you have uploaded your Excel file on any server and give the correct full path of that file. You can use the same code to convert CSV to JSON.

Here is our Test.xlsx file which looks like below

Output

When you host your index.html file on the server, on the page load we are running our script to show the objects in the browser console. Below is the output in JSON object

JSON Object output
JSON Object output

Download Excel to JSON javascript

You can use any one of the links to download the source code

  1. Google Drive: Download
  2. MediaFire: Download

I hope you liked this article. Please let us know if you face any issues in the comment sections below. Like our facebook page and subscribe to our newsletter for future updates. Have a great time! 🙂

Multi Level Cascading Dropdown for Sharepoint Online using REST Api

Hello Friends, in this tutorial we are going to implement Multi Level Cascading Dropdown in SharePoint Online custom Bootstrap form using REST api.

Multi Level Cascading Dropdown in SharePoint Online using REST

We have one list for City which has only one column named Title.

List Name : City
List Name : City

We have one list for State which has only one column named Title

List Name: State
List Name: States

We have one master list for all (Country, state and City) in which we are storing country values in Title field, State is a lookup field in which data is coming from State list, City is also a lookup column in which data is coming fom City list.

List Name: CountryStateCity
List Name: CountryStateCity

We have one custom bootstrap form in which we have 3 dropdowns which are Multi Level Cascading Dropdown, Country, State and City.

Html code:

<html>

<head>
    <title>Contact Form Tutorial by Bootstrapious.com</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="../CustomCode/referenceFiles/bootstrap.min.css" rel="stylesheet">
    <link href='../CustomCode/referenceFiles/googleFonts.css' rel='stylesheet' type='text/css'>
    <link href="../CustomCode/css/CustomCSS.css" rel="stylesheet">
</head>

<body>

    <div class="container">

        <div class="row">

            <div class="col-lg-8 col-lg-offset-2" id="form-body">

                <div id="main-form" role="form">

                    <div class="messages"></div>

                    <div class="controls">

                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_name">Firstname *</label>
                                    <input id="form_name" type="text" name="name" class="form-control" placeholder="Please enter your firstname *">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_lastname">Lastname *</label>
                                    <input id="form_lastname" type="text" name="surname" class="form-control" placeholder="Please enter your lastname *">
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_email">Email *</label>
                                    <input id="form_email" type="email" name="email" class="form-control" placeholder="Please enter your email *">
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="form-group">
                                    <label for="form_phone">Phone</label>
                                    <input id="form_phone" type="tel" name="phone" class="form-control" placeholder="Please enter your phone">
                                </div>
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="form_country">Country</label>
                                    <select class="form-control" id="form_country">
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="form_state">State</label>
                                    <select class="form-control" id="form_state">
                                    </select>
                                </div>
                            </div>
                            <div class="col-md-4">
                                <div class="form-group">
                                    <label for="form_city">City</label>
                                    <select class="form-control" id="form_city">
                                    </select>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col-md-12">
                                <div class="form-group">
                                    <label for="form_address">Address *</label>
                                    <textarea id="form_address" name="address" class="form-control" rows="4"></textarea>
                                </div>
                            </div>
                            <div class="col-md-12">
                                <input type="button" class="btn btn-success btn-send" value="Submit">
                            </div>
                        </div>

                        <div class="row">
                            <div class="col-md-12">
                                <p class="text-muted"><strong>*</strong> These fields are required.</p>
                            </div>
                        </div>
                    </div>

                </div>

            </div>
            <!-- /.8 -->

        </div>
        <!-- /.row-->

    </div>
    <!-- /.container-->

    <script src="../CustomCode/referenceFiles/jquery.min.js"></script>
    <script src="../CustomCode/referenceFiles/bootstrap.min.js"></script>
    <script src="../CustomCode/js/CustomJS.js"></script>
    <!--<script src="validator.js"></script>
 <script src="contact.js"></script>-->
</body>

</html>

This will look like

Multi Level Cascading Dropdown
SharePoint Bootstap form

When user selects Country, it will populate only those states which belongs to selected countris, when user select perticular state, it will populate only those cities which belongs to selected state.

here is the REST javascript file for Multi Level Cascading Dropdown:

$(document).ready(function() {
    appendCountries();
    $('#form_country').change(function() {
        appendStates();
    });
    $('#form_state').change(function() {
        appendCity();
    });
    $('.btn').click(function() {
        AddListItem();
    });
});

function appendCountries() {
    $.ajax({
        url: "../_vti_bin/ListData.svc/CountryStateCity()?$orderby= Title asc&$select=Title",
        type: "get",
        headers: {
            "Accept": "application/json;odata=verbose"
        },
        success: function(data) {
            var values = [];
            var uniqueValues = [];
            var option = "";
            var valuesArray = data.d.results;
            $.each(valuesArray, function(i, result) {
                values.push(result.Title);
            });
            $.each(values, function(i, el) {
                if ($.inArray(el, uniqueValues) === -1) {
                    uniqueValues.push(el);
                    option += "<option value='" + el + "'>" + el + "</option>";
                }
            });
            $("#form_country").append(option);
        },
        error: function(data) {
            alert(data.responseJSON.error);
        }
    });
}

function appendStates() {
    var country = $('#form_country').val();
    $.ajax({
        url: "../_vti_bin/ListData.svc/CountryStateCity()?$select=State&$filter=Title eq '" + country + "'&$expand=State&$orderby= State/Title asc",
        type: "get",
        headers: {
            "Accept": "application/json;odata=verbose"
        },
        success: function(data) {
            var values = [];
            var uniqueValues = [];
            var option = "";
            var valuesArray = data.d.results;
            $.each(valuesArray, function(i, result) {
                values.push(result.State.Title);
            });
            $.each(values, function(i, el) {
                if ($.inArray(el, uniqueValues) === -1) {
                    uniqueValues.push(el);
                    option += "<option value='" + el + "'>" + el + "</option>";
                }
            });
            $("#form_state").empty();
            $("#form_state").append(option);
        },
        error: function(data) {
            alert(data.responseJSON.error);
        }
    });
}

function appendCity() {
    var state = $('#form_state').val();
    $.ajax({
        url: "../_vti_bin/ListData.svc/CountryStateCity()?$select=City&$filter=State/Title eq '" + state + "'&$expand=State,City&$orderby= City/Title asc",
        type: "get",
        headers: {
            "Accept": "application/json;odata=verbose"
        },
        success: function(data) {
            var values = [];
            var uniqueValues = [];
            var option = "";
            var valuesArray = data.d.results;
            $.each(valuesArray, function(i, result) {
                values.push(result.City.Title);
            });
            $.each(values, function(i, el) {
                if ($.inArray(el, uniqueValues) === -1) {
                    uniqueValues.push(el);
                    option += "<option value='" + el + "'>" + el + "</option>";
                }
            });
            $("#form_city").empty();
            $("#form_city").append(option);
        },
        error: function(data) {
            alert(data.responseJSON.error);
        }
    });
}

function AddListItem()
{
    var firstName = $("#form_name").val();
    var lastName = $("#form_lastname").val();
    var email = $("#form_email");
    var phone = $('#form_phone');
    var country = $('#form_country');
    var state = $('#form_state');
    var city = $('#form_city');
    var address = $('#form_address');
    $.ajax({
        url: _spPageContextInfo.webAbsoluteUrl + "../_vti_bin/ListData.svc/EmployeeDetails()",
        type: "POST",
        data: JSON.stringify({
            __metadata:
            {
                type: "SP.Data.TestListItem"
            },
            FirstName: firstName,
            Lastname: lastName,
            Email: email,
            Phone: phone,
            Country: country,
            State: state,
            City: city,
            Address: address
        }),
        headers:
        {
            "Accept": "application/json;odata=verbose",
            "Content-Type": "application/json;odata=verbose",
            "X-RequestDigest": $("#__REQUESTDIGEST").val(),
            "X-HTTP-Method": "POST"
        },
        success: function(data, status, xhr)
        {
            alert('Request has been submitted successfully');
        },
        error: function(xhr, status, error)
        {
            //console.log(data.responseJSON.error);
            alert('Error');
        }
    });
}

You can download full code here: Download or use mediafire link or user Google Drive link.

I hope you liked this article. If you have any queries, feel free to ask in the comment section below. Like our facebook page and subscribe to our newsletter for future updates. Have a nice day!

Convert SharePoint Date to Readable date format using jquery

Hi friends, today we are going to see how to convert SharePoint date into human readable date format using jquery.

When you use REST API or JSOM to retrieve the date field from SharePoint, you will get the output as /Date(1508371200000)/. But what if you need it in a readable format?

We can easily convert above date format into a human-readable format using below script. Here

var rawDate = "/Date(1508371200000)/"; 
var rawDate = parseInt(rawDate.substring(6, 19)); 
var d = new Date(rawDate); 
var result = d.format("dd MMM yyyy");

In the above code, the variable result will give you the output as 19 Oct 2017

Convert SharePoint date to Readable date
Convert SharePoint date to Readable date

Recommended articles:

  1. CRUD Operations using REST API in SharePoint
  2. SharePoint Interview Questions
  3. SharePoint Content Types – Best Explained
  4. How to Make Conditionally Mandatory Field in SharePoint 2013
  5. SharePoint Site Columns – Best Explained

I hope you liked this article. Please feel free to ask your queries in the comment section below. Like our facebook page, and subscribe to our newsletter for future updates. Have a nice day!

How to Display SharePoint List in jQuery Datatables

Hello friends, in this article we are going to retrieve data from SharePoint List using REST API and will display that data into jQuery Datatable. So let’s begin…

Show SharePoint List in Datatable format

Step 1:

We have a SharePoint list named EmployeeDetails as shown below with some dummy data. This list has 4 columns (Title, Name, Salary, Address).

EmployeeDetails List
EmployeeDetails List

Step 2 : Create a site page where we are going to show above data in datatable. For creating a page go to Site contents > Site pages > Click on new page icon. In this case I have created a page with name Employee Details.

Step 3 : Insert a Content Editor Webpart into a page.

Employee Details Page
Employee Details Page

Step 4 : Edit the Content Editor Webpart and paste the below code into it.

 

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.datatables.net/1.10.9/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.9/css/jquery.dataTables.min.css" rel="Stylesheet" type="text/css" />
<script type="text/javascript" src="../SiteAssets/EmployeeJqueryDatatable.js"></script>
<div id="DatatablePanel">
    <table style="width: 100%;">
        <tr>
            <td>
                <div id="DatatableGrid" style="width: 100%"></div>
            </td>
        </tr>
    </table>
</div>

download above html file here. (or you can use MediaFire link)

Step 5 : If you can observe the above code, we have referenced a .js file named EmployeeJqueryDatatable.js So we have to first create this js file and upload it into Site assets. Please copy the below code into this js file and named it as EmployeeJqueryDatatable.js

$(document).ready(function() {
    var RestUrl = "../_vti_bin/listdata.svc/EmployeeDetails";
    $.ajax({
        url: RestUrl,
        method: "GET",
        headers: {
            "accept": "application/json;odata=verbose",
        },
        success: function(data) {
            if (data.d.results.length > 0) {
                //construct HTML Table from the JSON Data
                $('#DatatableGrid').append(GenerateTableFromJson(data.d.results));
                //Bind the HTML data with Jquery DataTable
                var oTable = $('#EmployeeTable').dataTable({
                    "iDisplayLength": 5,
                    "aLengthMenu": [
                        [5, 10, 30, 50],
                        [5, 10, 30, 50]
                    ],
                    "sPaginationType": "full_numbers"
                });
            } else {
                $('#DatatableGrid').append("<span>No Employee Details Found.</span>");
            }
        },
        error: function(data) {
            $('#DatatableGrid').append("<span>Error Retreiving Employee Details. Error : " + JSON.stringify(data) + "</span>");
        }
    });

    function GenerateTableFromJson(objArray) {
        var tableContent = '<table id="EmployeeTable" style="width:100%"><thead><tr><td>Title</td>' + '<td>Name</td>' + '<td>Salary</td>' + '<td>Address</td>' + '</tr></thead><tbody>';
        for (var i = 0; i < objArray.length; i++) {
            tableContent += '<tr>';
            tableContent += '<td>' + objArray[i].Title + '</td>';
            tableContent += '<td>' + objArray[i].Name + '</td>';
            tableContent += '<td>' + objArray[i].Salary + '</td>';
            tableContent += '<td>' + objArray[i].Address + '</td>';
            tableContent += '</tr>';
        }
        return tableContent;
    }
});

download above .js file here (for security reasons I have used .txt file here, so after downloading rename it to .js) or you can use MediaFire link to download the direct js file here

Step 6 : Once you upload the above js file into your site assets, go to our EmployeeDetails page that we ceated in step no. 2. Here we go!!! below is the output for our EmployeeDetails list

Video tutorial:

I have also created a step by step video tutorial for SharePoint Datatables. Please watch it for clear understanding:

https://www.youtube.com/watch?v=gXoeBrXSb3A

I would like to reply to your queries. Please let me know whether you liked this simple step by step article on SharePoint Datatable integration. I am waiting for your comments! Please like our facebook page and subscibe to our newsletter for future updates. Have a nice day!