Sunday, 1 September 2013

OTB SharePoint forms and jQuery


SharePoint Forms and jQuery
Sunday, 1 September 2013
3:06 PM
For OTB forms SharePoint uses the hierarchy of UI controls to create the "id" and "name" attributes for their fields. This is a functionality that SharePoint inherits from ASP .NET

Sometimes you may want to get a 'hook' on one or several of these fields, without modifying the OTB form, to apply styles or modify the control behaviours  (i.e. make them read only). 
Since the developer doesn't have any control on the name and id attributes generated by SharePoint another attribute must be used to effectively get a reference to any of the fields.
First let see an illustration of the html mark-up generated by SharePoint and then we will see another attribute that can be used to get a reference to a field or fields in a SharePoint OTB Form.
If You go to an OTB document library such as the Document library and click on "new document". You will get a form, for adding a new document, consisting of a single input field with a browse button.
 









Using your favourite browse you can inspect the name and id that SharePoint (ASP .NET really) render/creates on the client side.
 






In this case we can observe that the name of the field is made of the Main Content control ID plus the name of the section where the field lies, which in this case happen to be a table row ( Html element),  plus the Input field own id. The main content control is the asp:content control that you see on the form should you open it with SharePoint designer:  <asp:Content ContentPlaceHolderId="PlaceHolderMain" runat="server">
 
There is another property that gets generated and it "title" As you can see from the screen shot below the title attribute of this field is "Choose a File"



Using the title attribute we can get a hook or reference to this field and perform operations on it like we would on any HTML Element using jQuery:

 //we hide the field by using the whole title property
("[Title='Choose a file']").hide();

//we hide any field starting with the term 'Choose'
["[Title^='Choose']").hide()

 //we hide any field ending with the term 'file'
["[Title$='file']").hide()
The cool thing about jQuery wildcard selectors is that if you have several fields that have a title attribute starting or ending with a common term such as 'employee' and you want to apply the same operation to all of them then you can do with a single line of code.

["[Title^='employee']").attr('disabled','disabled')

This would make any field with a title starting with 'employee' a read-only field.

No comments:

Post a Comment