SharePoint Get GUID Of List and Columns

While developing SharePoint solution code we require GUID of List and Columns Id.We can easily get this using below format

Custom List:

Note that this list has 2 columns
1.Title
2.Target
To view GUID for this list Navigate to list settings.

Once we Navigate to List settings we are able to see below URL. Copy Full URL from browser

https://onsps.sharepoint.com/_layouts/15/listedit.aspx?List=%7B2CB2E87A-04CD-445A-9201-4F41FD8EF9A1%7D 

Replace the following characters as follows:
%7B to {
%2D to –
%7D to }

Once you replace above encoded character then list GUID will available which is {2CB2E87A-04CD-445A-9201-4F41FD8EF9A1}

To View all Columns and files inside this list change or append URL as below

https://onsps.sharepoint.com/_vti_bin/owssvr.dll?Cmd=ExportList&List=2CB2E87A-04CD-445A-9201-4F41FD8EF9A1

When we type above url it will open or download xml file which file has all information regarding list and its columns with GUID.

Here SourceID indicates GUID for List and ID indicates Column ID.

SharePoint: CRUD Operation using SPServices

Fill Drop Down List:

<script language="javascript" type="text/javascript">

/* ----------- Bind Dorp Down List - Country Begin -------------*/
var SPSiteURL = "https://yourSharepointsiteURL/Site";
 
        $().SPServices({
            webURL: SPSiteURL,
            operation: "GetListItems",
            async: false,
            listName: "Country",
            CAMLQuery: "<Query><OrderBy><FieldRef Name='Title'/></OrderBy><Where><Eq><FieldRef Name='Active'/><Value Type='Boolean'>1</Value></Eq></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>",
            completefunc: function(xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    var DataTextField = $(this).attr("ows_Title");
                    var DataValueField = $(this).attr("ows_ID");
                    listItem = "<option value=" + DataValueField + ">" + DataTextField + "</option>"
                    $("#ddlCountry").append(listItem);
                });
            }
        });
/* ----------- Bind Dorp Down List - Country End -------------*/
</script>

Above Code will get items from Country DropDownList where Active = True

Save:
Bind Save Button Event & Code to Save Data.

<script language="javascript" type="text/javascript">

//Submit Button Click Event
    $("#btnSubmit").click(function() {
        return SaveEmployeeInfo();
    });

/* ----------- Save Employee Info Form Code Begin -------------*/
function SaveEmployeeInfo()

{
    console.log("Save Process Begin");
    //alert("Save Event");

    var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    console.log("City = " + City);   

    console.log("Save Process Begin");

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get Item CreationInfo 
    var itemCreateInfo = new SP.ListItemCreationInformation();

    //Add Item Object
    this.oListItem = oList.addItem(itemCreateInfo);

    //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);
	

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onSaveQuerySucceeded), Function.createDelegate(this, this.onSaveQueryFailed));

    return false;
}

function onSaveQuerySucceeded() {

    console.log('Item created: ' + oListItem.get_id());
}

function onSaveQueryFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>

Update: Bind Update Button Event & Code to Update Data

<script language="javascript" type="text/javascript">


/* ----------- Update Employee Info By EmpID Code Start-------------*/
function UpdateEmployeeInfo() {
    
	//alert("Update Operation Begin");
	
    var EmpID = getParameterByName('EmpID');
	
	var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
	console.log("City = " + City);  
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get List Item By ID 	
    this.oListItem = oList.getItemById(EmpID);

   //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryAuditUpdateSucceeded), Function.createDelegate(this, this.onQueryAuditUpdatedFailed));

    return false;


}

function onQueryAuditUpdateSucceeded() {

    console.log('Item Updated Successfully');
}

function onQueryAuditUpdatedFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
/* ----------- Update Employee Info By EmpID Code End-------------*/

</script>


Retrieve Employee Data : Code to Retrieve Data

<script language="javascript" type="text/javascript">

/* ----------- Retrieve Employee Data Code Starts -------------*/
function GetemployeeData(EmpID) {
    $().SPServices({
        webURL: SPARPSiteURL,
        operation: "GetListItems",
        async: false,
        listName: "EmployeeInfo",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + EmpID + "</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='EmployeeName' /><FieldRef Name='City' /><FieldRef Name='Agreement' /><FieldRef Name='Hobbies' /><FieldRef Name='BirthDate' /></ViewFields>",

        completefunc: function(xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function() {

                console.log("ows_Title " + $(this).attr("ows_Title"));
                console.log("ID " + $(this).attr("ows_ID"));
                console.log("EmployeeName " + $(this).attr("ows_EmployeeName"));
                console.log("City " + $(this).attr("ows_City"));
                console.log("Agreement " + $(this).attr("ows_Agreement"));
                console.log("Hobbies " + $(this).attr("ows_Hobbies"));
                console.log("BirthDate " + $(this).attr("ows_BirthDate"));
              
                var City = $(this).attr("ows_City");
                $("#ddlCity").find("option:contains('" + City + "')").each(function() {
                    if ($(this).text() == City) {
                        $(this).attr("selected", "selected");
                    }
                });


                $("#txtEmployeeName").val($(this).attr("ows_EmployeeName"));

                var date = new Date($(this).attr("ows_BirthDate"));
                if (!date) {
                    var currentMonth = date.getMonth() + 1;
                    if (currentMonth < 10) {
                        currentMonth = '0' + currentMonth;
                    }
                    var currentDate = date.getDate();
                    if (currentDate < 10) {
                        currentDate = '0' + currentDate;
                    }
                    var PrePlanStartDate = (currentDate) + '/' + currentDate + '/' + date.getFullYear();
                    $("#txtBirthDatee").val(PrePlanStartDate);
                }

                if ($(this).attr("ows_Agreement") == 1) {
                    $('#chkAgreement').attr('checked', 'checked');
                };

                //---------Hobbies Check Box List
                console.log("Hobbies Value " + $(this).attr("ows_Hobbies"));
                var Hobbies = $(this).attr("ows_Hobbies");

                var arrayTeam = Hobbies.split(',');
                //console.log("Array Value" + arrayTeam);

                for (var i = 0; i < arrayTeam.length; i++) {
                    var chkValue = arrayTeam[i];
                    $("#chkHobbies input:checkbox").each(
                        function() {
                            if ($(this).attr("id") == chkValue) {
                                $(this).prop("checked", true);
                            }
                        }
                    );
                }

            });
        }
    });
}
/* ----------- Retrieve Employee Data Code Ends -------------*/
</script>

SharePoint 2010 List View Search as you type in Textbox

Title: SharePoint Content Query Search
We can search from existing list using textbox search using jQuery and List view.
Follow below steps to search in list using Textbox.
1.Add Textbox using Content Editor Web Part on Page.
2.Create List View which you want to appear on Page.

Once above things available on Page use below JavaScript Code which is responsible to search from list view using textbox.


<script language="javascript" type="text/javascript">

$(document).ready(function() {

    // SharePoint List View Table 
    var list = $("table.ms-listviewtable");
    // Table row of the items in list.
    var listItems = $("table.ms-listviewtable tr:not(.ms-viewheadertr)");
    // Our filter input.
    var input = $("input#filterInput");

    input.keyup(function() // On key presses
        {
            listItems.each(function() // for each items in list
                {
                    var text = $(this).text().toLowerCase(); 
                    console.log(text);
                    if (text.indexOf(input.val()) != -1) 
                    {
                        $(this).show(); 
                    } else {
                        $(this).hide(); 
                    }
                });
        });


});
</script>

After adding script, we are able to search from textbox’s key press event or as you type in textbox.

For this example, I have used Color List for demonstration and I am filtering list using color name.

Control Validation using jQuery

Validation is key important point for any application. In Website we need to validate control or inputs immediately after user enters values in controls.

This can be achieved by below code.


<!DOCTYPE html>
<html lang="en">
<head>
    <title>Bootstrap Example</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script>
        $(document).ready(function() {
           
        });

        function ValidateEmail() {
            var emailReg = /^([\w-\.]+@([\w-]+\.)+[\w-]{2,4})?$/;
           
		   var emailaddress = $("#Email").val();
			
            if (!emailaddress) {
                $("#emailspan").html('<font color="#cc0000">Please enter Email </font>');
                return false;
            } else {
			 $("#emailspan").html('<font color="#cc0000"></font>');
                return true;
            }

            if (!emailReg.test(emailaddress)) {
                $("#emailspan").html('<font color="#cc0000">Please enter valid Email address</font>');
                return false;
            } else {
                $("#emailspan").html('<font color="#cc0000"></font>');
                return true;
            }
        }

        function checkPassowrd() {
            var password = $("#pwd").val();
            if (!password) {
                $("#passwordspan").html('<font color="#cc0000">Please enter Password</font>');
                return false;
            } else {
				$("#passwordspan").html('<font color="#cc0000"></font>');
                return true;
            }
        }

        function validateform() {
            var result = false;
			var res = ValidateEmail();
			var res1 = checkPassowrd();
			
            if (res == true && res1 == true) {
                result = true;
            }
            return result;
        }
    </script>
</head>

<body>
    <div class="container">
        <h2>Validation</h2>
        <form>
            <div class="form-group">
                <label for="email">Email:</label>
                <input type="text" id="Email" class="form-control" name="Email" maxLength="50" size="45" onblur="ValidateEmail()" /><span id="emailspan" value="0"></span>

            </div>
            <div class="form-group">
                <label for="pwd">Password:</label>
                <input type="password" class="form-control" id="pwd" placeholder="Enter password" name="pwd" onblur="checkPassowrd()"><span id="passwordspan" value="0"></span>
            </div>
            <div class="checkbox">
                <label>
                    <input type="checkbox" name="remember"> Remember Me</label>
            </div>
            <button type="submit" class="btn btn-default" onclick="return validateform()">Submit</button>
        </form>
    </div>
</body>
</html>

Above Code will display page as below

When User click on Submit button it will show error message as below.

When I enter email value it will remove error message as shown in below Image

Note that we require jQuery  for this validation.

Retrieve QueryString Parameter Value using jQuery

To Retrieve query string parameter using jQuery use below code

<script language="javascript" type="text/javascript">
/* ----------- Get QueryString Parameter Code Starts -------------*/
function getParameterByName(name, url) {

        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));

 }
/* ----------- Get QueryString Parameter Code End -------------*/
</script>

Use above function to get Parameter Value

<script language="javascript" type="text/javascript">
$(document).ready(function() {
    var para = getParameterByName('EmpID');
});
</script>

SharePoint SPServices Check User Group

To check Logged in user group using SPServices use below code.

<script language="javascript" type="text/javascript">

$(document).ready(function() {
    CheckUserGroup();
});

/* ----------- Check User Group Code Begin -------------*/
function CheckUserGroup(itemid) {
        $().SPServices({

            operation: "GetGroupCollectionFromUser",

            userLoginName: $().SPServices.SPGetCurrentUser(),

            async: false,

            completefunc: function(xData, Status) {

                if ($(xData.responseXML).find("Group[Name = 'Administrator']").length == 1) {

                    alert("Logged In User Group :: Administrator ");

                    /* ----------- Enable Disable Control Start -------------*/

                    //$("#divEmployee :input").prop("disabled", true);

                    //$("#btnSubmit").removeAttr('disabled');

                    /* ----------- Enable Disable Control End -------------*/

                } else {

                    alert("Logged In User is OutSide Of Adnministrator Group");
                }

            }

        });
    }
/* ----------- Check User Group Code End -------------*/
</script>

SharePoint Date Conversion to Javascript MM/DD/YYYY Format

To covert SharePoint Date to JavaScript Date Format MM/DD/YYYY use below code.


<script language="javascript" type="text/javascript">
/* ----------- SharePoint Date To JavaScript Date Format Code Start -------------*/
function convertSPDate(d) {
/*
* A function to convert a standard SharePoint
* date/time field (YYYY-MM-DD HH:MM:SS) to a
* javascript Date() object
*
* Author: Ben Tedder (www.bentedder.com)convertSPDate
*/
// split apart the date and time
var xDate = d.split(" ")[0];
var xTime = d.split(" ")[1];

// split apart the hour, minute, & second
var xTimeParts = xTime.split(":");
var xHour = xTimeParts[0];
var xMin = xTimeParts[1];
var xSec = xTimeParts[2];

// split apart the year, month, & day
var xDateParts = xDate.split("-");
var xYear = xDateParts[0];
var xMonth = xDateParts[1]-1;
var xDay = xDateParts[2];

var dDate = new Date(xYear, xMonth, xDay, xHour, xMin, xSec);
return dDate;
}
/* ----------- SharePoint Date To JavaScript Date Format Code End -------------*/

</script>

We also require moment.js to format it in MM/DD/YYYY Format


var DOB = new convertSPDate($(this).attr("ows_DOB"));
$("#txtDOB").val(moment(DOB).format('L'));

Moment JS Reference URL:
http://momentjs.com/
http://momentjs.com/downloads/moment.min.js