Add jQuery to SharePoint

Disclaimer

I am referring to SharePoint 2010, I have used my Foundation version instance. I have not tested this in SharePoint 2013 but I think some information here are absolutely good for it.
There are some ways to accomplish this task, I show you the best and I will motivate it.

Get jQuery

First of all you need to download the jQuery minified of the version you want, usually the last one is the right choice if you have not particular needs (jQuery download page). The current latest one is jquery-1.10.1.min.js file.

Put jQuery on SharePoint folder

On SharePoint server you have to go in the “LAYOUTS” folder and create a folder for your site, it will be useful for more files other than jQuery. Then add a “Scripts” folder. I remember you that the 14 folder is usually in C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14.
So now you have ..\14\TEMPLATE\LAYOUTS\[MySite]\Scripts. [MySite] in my case is “portal.alex75.it” (yes, with dots in the name), exactly the site collection I am using for this example.
Put in this folder the downloaded jQuery file.

Add script reference in master page

The master page that you must edit for sure is the v4.master. After you test the result is ok on it you can do the same thing for the others, they can be used in some circumstances, this is an explanation of their roles:
v4.master > The default master page.
default.master > It is used to support the 2007 user interface.
minimal.master > It is used for the requests from mobile devices
simple.master > It is used for accessdenied.aspx, confirmation.aspx, error.aspx, login.aspx, reqacc.aspx, signout.aspx and webdeleted.aspx pages (I haven’t this one in my SharePoint 2010 Foundation).

With SharePoint Designer use the context menu (right click) on the master you want to edit and select “Edit file in advanced mode“.
You have can find “<SharePoint:CustomJSUrl runat=”server” />” and add the script after this. It is after “core.js”.
It is important that the script you add (jQuery reference) is before the “<asp:ContentPlaceHolder id=”PlaceHolderAdditionalPageHead” runat=”server”/>” because in this manner jQuery was loaded before additional scripts in .aspx pages, in fact additional scripts in pages are added in this place holder.
So the result can be something like this:
jQuery Script in master page
I omit type on script element because I use to change the doctype to HTML5 (<!DOCTYPE html>).
In HTML5 script tag has default for type as “text\javascript” thus it is not needed.
You can use this:

Details and comment

The “official” way to add a script is using the SharePoint:ScriptLink tag but if you not need to use “SP” namespace (or other dependencies) the simplest HTML syntax is the best.
The “official” folder to add things like scripts and images is the Style Library folder but for a bug requests on this path are returned with a HTTP 304 response, so the “refresh” of the files are sometimes impeded. Now, there is the “Site Assets” library but this one is accessed by users with interface and I prefer not to risk someone modify or delete files so important.

Example code for cut&paste

<SharePoint:ScriptLink language="javascript" name="core.js" OnDemand="true" runat="server"/>
<SharePoint:CustomJSUrl runat="server" />
<!-- customization -->
<script type="text/javascript" src="/_layouts/portal.alex75.it/Scripts/jquery-1.10.1.min.js"></script>
<script>alert("jQuery version: " + $.fn.jquery);</script>
<SharePoint:SoapDiscoveryLink runat="server"/>
<asp:ContentPlaceHolder id="PlaceHolderAdditionalPageHead" runat="server"/>

SharePoint 2010 – set fields read only or hidden

An updated version of this article can be found here: alex75.it/sharepoint/set-field-read-only.

Goal

1) Set some fields “read only” in “Edit” modal windows of a list item.
2) Hide some fields in “New”, “Display” and “Edit” modal windows.

Prerequisites

SharePoint 2010 site
base of javascript
SharePoint Designer that can access to site

Content

The example is based on a custom list (“Protocol”). I start with an example that use “inline” javascript, and then some words on better approach with external javascript inclusion.
Start the work. Open with SharePoint Designer the “EditForm.aspx” of the list and in advanced mode. You MUST use “Edit in advanced mode” by right click menu to be enabled to changing everything in the .aspx).
Search the “PlaceHolderAdditionalPageHead” id tag in the page:

javascript place in SharePoint 2010

Insert this excerpt of code after the row with “<SharePoint:CssRegistration Name=”forms.css” runat=”server”/>”:

<!-- customization 1 -->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>

<script type="text/javascript">
var $headers;   //collection of field labels
function getFieldRow(displayName) {
   if (!$headers)
       $headers = $('h3.ms-standardheader');

   var $header = $headers.find(':contains("'+displayName+'")'); // parent of <nobr>
   if($header)
       return $header.parents('tr')[0]; // first ancestor 'tr'
   else
       return null;  // not found

   // example of header with mandatory symbol
   // <nobr>Title<span class="ms-formvalidation" title="This is a required field."> *</span></nobr>  
}

function setReadOnly(displayName) {
   var row = getFieldRow(displayName);
   if (!row)
       alert("Field \"" + displayName + "\" not found.");

   var $input = $(row).find('input[type="text"]');   // find the text box

   var text = $input.val();
   $input.hide()                     // remove also field description
   $( $input.parents('td')[0] ).text(text);   
}

function hideField(displayName) {
   var row = getFieldRow(displayName);
   if (!row)
       alert("Field \"" + displayName + "\" not found.");

   $(row).hide();
}

//call to “hide” and “set read-only” functions
$(function () {       // short-hand for $(document).ready()
   hideField("Field 1");
   hideField("Field 2");
   setReadOnly("Field 3");
   setReadOnly("Field 4");
});
</script>

The first operation is for including an external jQuery file.

I’ve used the Microsoft CDN but you can use the local (“LAYOUT” folder) file or another CDN ( ref: docs.jquery.com/Downloading_jQuery).

The second part is the definition af the function that search the row (TR) where field is rendered (“getFieldRow”). It search the field by its “display name”, so you have to check out for language pack or different localization.

The function return null if field is not found. Is your work to check for this.

The other functions (“setReadOnly” and “hideField”) are self explanatory. This simple version of “setReadOnly” works only on “text” type imput controls.

The last part is final call of functions on page fields. Calls are made after DOM is full loaded (jQuery “ready()” on “document”), so all controls exists in the document.

It hide “Field 1” and “Field 2” (in the example “”) (in the example “Year” and “Counter”)

My form in “New” visualization is this:

and in original “Edit” mode:

This is the result of customization:

Note that the field description (in “Counter” field) is removed too.

The above example use a “inline scripts” approach. Of course a better way is to register the function in a external javascript file that can be used all the time we need, and obviously make code more simple to change, and page more light. Also for this purpose I’ve separate the code in more than a unique function, to make code more reusable.
When the javascript is in a external file we can use only this code to make all the work (note the inclusion of “my_project.js”):

<!-- customization 4 -->
<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.7.1.min.js"></script>
<script type="text/javascript" src="/_layouts/My_Customer/JS/my_project.js"></script>   
<script type="text/javascript">
    $(function () {
        hideField("Accounts");
        hideField("Category");
        setReadOnly("All Day Event");
        setReadOnly("Workspace");
    });
</script>

End.