Archive

Posts Tagged ‘JQuery’

Good site for learning promises with jQuery

Hi everybody,

I know it has been a while since I have personally blogged… whilst in a quiet period in my role I decided to teach myself JavaScript promises via jQuery.

This site was invaluable: http://www.htmlgoodies.com/beyond/javascript/making-promises-with-jquery-deferred.html

Till the next time…

Cheers

Giles

Categories: Work Tags: , ,

How do I: Set the ID attribute of a table row using jQuery and SharePoint Designer

November 9, 2012 Leave a comment

While customizing an “add new item” form, you might find yourself needing to manipulate form elements via jQuery. However, before you can do that you must and an #id or .class to the elements in question. I will be adding an #id in this demonstration. But why would I want to manipulate form elements in the first place? If you wanted to hide/show a textbox based on the user selection of a checkbox you could use this technique.

Get the code

Related videos:

Hiding/Showing InfoPath 2010 form element using jQuery

November 3, 2012 Leave a comment

Get the code / Look for the highlight area

InfoPath 2010 is a great tool. However, while building forms in InfoPath it’s only a matter of time when you have a user requirment that InfoPath alone simply will not do. In that case you might have a few options. You could add custom code using VSTA, which means you will need to publish them as an administrator approved form template.You could ditch InfoPath completely and build your forms in Visual Studio 2010 using asp.net. You could build them using the client object model. Lots to think about. In addtion, you could manipulate some form element using jQuery. The video demonstrates a simple way to hide/show a textbox element using jQuery.

Using jQuery to hide form elements based on checkbox value

November 1, 2012 Leave a comment

Let’s say you wanted to hide/show a specific textbox only if a specific checkbox has been selected. You can use jQuery to do this via SharePoint Designer 2010

How can I validate a textbox using the PreSaveAction()

How do I: Create a simple form to collect data in SharePoint 2010

How can I hide/show a textbox based on a radio button selection?

How can I hide/show a textbox based on a drop-down value?

Hiding and showing fields using jQuery in SharePoint Designer 2010

October 25, 2012 1 comment

Building forms using SharePoint Designer can be a bit tricky at times. What if you wanted to a text box to show only if a certain radio button value is selected? This video will show you how I acheived this using jQuery.

Get the code

This post might also help:
Validating a SharePoint form field in SharePoint Designer 2010

Using jQuery to hide form elements based on drop-down value

October 25, 2012 Leave a comment

Using jQuery to hide form elements based on drop-down value.

#SP2010 web part rounded corners #SharePoint #PS2010 #ProjectServer #MSProject #in

April 25, 2012 7 comments

At one of my clients I was asked to document how we achieved rounded corners on web parts. So as a result, I figured a blog post about it would be useful.

Now when I first implemented this (almost 2 years ago!) as the 2010 product RTM’d, I based it on the only blog post around at the time:

    The end result looks like this:

ChromeTitleAndBorder

NB: Please note that this version is slightly modified from the version supplied on the blog link above.

In my implementation I was using the jQuery version available at the time:

  • jQuery 1.5.1
  • jQuery UI 1.8.13

Although jQuery UI is not required, it is always good to have for those awesome calendar pop-ups just in case.

This may work with the newer versions of jQuery, but I haven’t tried it out yet.

Example CSS, JavaScript and rounded corner image files are provided at the bottom of the post.

So without further ado, lets go through how to achieve the rounded corners in SharePoint 2010:

What does the code actually do?

With every page refresh, the JavaScript code, determines where all the web parts on the page are and injects appropriate mark up (<DIV>) above and below each web part, ready to be styled by CSS.

Step 1. Upload your reference files

Personally I like to store all my custom files within the Style Library within SharePoint, but they can live anywhere within SharePoint as long as all users have read access to them.

So lets take a look at what we are storing.

Standard Plug-In Files:

  • jquery-ui-1.8.13.custom.css
  • jquery-1.5.1.min.js
  • jquery-ui-1.8.13.custom.min.js

You can download this version here:

The latest versions are available here:

Custom Files

  • <custom JavaScript file>.js
  • <custom CSS file>.css

These files are where we will implement the JavaScript and CSS code to produce the rounded corners on each web part.

Corner Image Files

The following files are used to create the rounded corner affect. To keep multi-browser support we are using this method, but you could replace them with CSS3 styling by changing the CSS code to achieve the same result.

  • WPBottomLeft.gif
  • WPBottomRight.gif
  • WPTopLeft.gif
  • WPTopRight.gif

Example files are provide below.

Step 2. Add your Master Page file references

Initially add the following references into <head> section of your Master Page, preferably just before the end tag </head>

<link type="text/css" href="/Style Library/jquery-ui-1.8.2.custom.css" 
rel="Stylesheet" />

<script src="/Style Library/jquery-1.4.2.min.js" 
type="text/javascript"></script>

<script src="/Style Library/jquery-ui-1.8.2.custom.min.js" 
type="text/javascript"></script>

Now the above references are just standard plug-ins available from the jQuery website, but we also need to add some of our own JavaScript / jQuery magic, which of course needs its own reference file.

<script src="/Style Library/<customJavaScriptFile>.js" type="text/javascript"></script>

We also need to reference a custom CSS file, so that we can associate the corner images we will be using etc…

Publishing Feature enabled?

Now if you are using the Publishing feature, you can place your custom CSS via the Site Settings interface:

Site Actions > Site Settings > Under Look and Feel – Click “Master Page”

Under the “Alternate CSS URL”, enter the URL for your custom CSS file, for example:

  • /style library/<customCSSFile>.css
    NB: This will ensure it is the last CSS file referenced within the Master Page to allow for overrides.

Publishing Feature not-enabled?

If you you do not have the publishing feature enabled (Office 365 P1 or SharePoint Foundation 2010 for example), you can add the reference into the Master Page also.

<link type="text/css" href="/Style Library/{customCSSFile}.css" 
rel="Stylesheet" />

Step 3. Adding the code

So now that we have our JavaScript, jQuery and CSS files setup in the Master Page, we can edit out custom files with the following code:

CSS Code (customCSSFile.css)

/* Web Part Chrome Styles – START */

.wpContainer {
padding-bottom:0px !important;
}
.wpTitleBorder, .wpBorderOnly {
background-color:#fff !important;
border-left:1px solid #c6c6c5 !important;
border-right:1px solid #c6c6c5 !important;
}
.ms-WPHeader td {
background-color:#ffffff !important;
border:0 !important;
padding:0 !important;
padding-top: 3px !important;
border-bottom: 1px #CECFCE solid !important;
}
h3.ms-WPTitle {
/* color:#36424a !important; */
font-size:15px !important;
font-weight:normal !important;
margin:-3px 0 0 0px !important;
padding:0 14px 4px 4px !important;
}
h3.ms-WPTitle a {
/* color:#36424a !important; */
font-size:15px !important;
font-weight:normal !important;
}
h3.ms-WPTitle nobr {
white-space:normal !important;
}
.ms-WPHeader td div.ms-HoverCellInActive {
margin:0 !important;
*padding:0 0 2px 0 !important; /* IE <8 fix */
}
.ms-WPHeader td .ms-HoverCellInActive {
margin:0 !important;
*padding:0 0 2px 0 !important; /* IE <8 fix */
}
.ms-WPHeader td .ms-HoverCellInActive img {
margin:0 0 2px 0 !important;
*margin:0 !important; /* IE <8 fix */
}
.ms-WPHeader img.ms-HoverCellInActive { /* Firefox */
padding:0 0 2px 0 !important;
}
.ms-WPHeader td .ms-HoverCellActiveDark {
border:0 !important;
margin:0 !important;
padding:0 0 2px 0 !important;
}
td.ms-WPBorder, td.ms-WPBorderBorderOnly {
border:0 !important;
padding:0px 0px !important;
}
.ms-WPBody {
font-family:Tahoma, arial, sans-serif !important;
font-size:11px !important;
padding:0 !important;
}
.ms-WPBody td, .ms-WPBody TD DIV, .ms-WPBody TD DIV A {
font-family:Arial, Tahoma, sans-serif !important;
font-size:11px !important;
}
.wpCornersTop {
background:url('/blog/Style Library/Images/WPTopRight.gif')
 top right no-repeat !important;
height:10px !important;
padding-right:10px !important;
}
.wpCornersTop div {
background:url('/blog/Style Library/Images/WPTopLeft.gif')
 0 0 no-repeat !important;
height:10px !important;
}
.wpCornersBtm {
background:url('/blog/Style Library/Images/WPBottomRight.gif')
 bottom right no-repeat !important;
height:11px !important;
padding-right:11px !important;
}
.wpCornersBtm div {
background:url('/blog/Style Library/Images/WPBottomLeft.gif')
 0 0 no-repeat !important;
height:11px !important;
}

/* Web Part Chrome Styles - STOP */

JavaScript / jQuery Code (customJavaScriptFile.js)

function wrapWebParts() {

//Find all divs (div.ms-WPBody) with an ID beginning
//with "WebPart". All web parts have unique IDs assigned
//to them, and they begin with "WebPart". Then traverse up
//the HTML document 4 levels and add the class "wp".

  $('td[id*=MSOZoneCell_WebPart]').children("table").addClass("wp");

//For web parts with the Title and Border chrome,
//add the class "wpTitleBorder" to the element
//with class "wp".

  $(".ms-WPBorder").parents(".wp").addClass("wpTitleBorder");

//For web parts with the Border Only chrome, add the class
//"wpBorderOnly" to the element with the class "wp".

  $(".ms-WPBorderBorderOnly").parents(".wp").addClass("wpBorderOnly");

//Find all table cells that have an ID beginning with
//'"MSOZoneCell" and add the class "wpContainer".

  $("td[id^=MSOZoneCell]").addClass("wpContainer");

//For web parts with the chrome type Title and Border or Border Only,
//add containers that can be used for rounded corners and other
//treatments

  //alert($(".wpTitleBorder").length);
  $(".wpTitleBorder").before('<div class="wpCornersTop"><div></div></div>')
     .after('<div class="wpCornersBtm"><div></div></div>');

  $(".wpBorderOnly").before('<div class="wpCornersTop"><div></div></div>')
     .after('<div class="wpCornersBtm"><div></div></div>');

  $("img[src*=/_layouts/images/blank.gif]")
    .attr("style", "display: none;");

  $('div[class=wpCornersBtm]').each(function() {
    var mainWPTable = $(this).prev();
    var inlineWidthStyle = mainWPTable.attr("style");
    var realWidthSplit = "";
    var realWidth = "";

    if (inlineWidthStyle != undefined) {
      realWidthSplit = inlineWidthStyle.split(":");
       realWidth = realWidthSplit[1].toLowerCase();
       realWidth = realWidth.replace("px", "");
       realWidth = parseInt(realWidth, 10);
       realWidth = realWidth + 13;

       $(this).attr("style", "width: " + realWidth + "px");
       $(this).prev().prev().attr("style", "width: "
          + realWidth + "px");
    }

  });

}

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

And Finally…

The end result is this:

ChromeTitleAndBorder

If we break this down, the jQuery code has discovered each web part on the page, added a <div> above and below the web part and then the CSS has styled it with the supplied image files referenced in the style sheet.

WPImageExample

The code also takes into account the chrome type being used on the web part:

This results in the following:

Chrome Type: None

ChromeTypeNone

Chrome Type: Title and Border

ChromeTitleAndBorder

Chrome Type: Title Only

ChomeTypeTitleOnly

Chrome Type: Border Only

ChromeTypeBorderOnly

Code Downloads:

Calculated Column Formula: Probability and impact analysis for risks #SharePoint #SP2010 #ProjectServer #PS2010 #EPM #MSProject #in

March 9, 2011 2 comments

Many project managers like to do risk analysis in terms of probability and impact, ultimately creating a heat map when data is rolled up at the project or programme level.

Further information about the methodology can be found here: http://www.expertprogrammanagement.com/2010/06/project-risk-management/

To aid in the creation of these roll up dashboards, we need to evaluate each risk as it is entered (and updated) and assess the probability of the risk occurring against the impact it has against the project (normally in terms of Cost, Resource or Time).

The following chart details this analysis:

probabilityVsImpact

NB: Numeric values have been assigned for the formulas listed below

To implement this in SharePoint (either standalone or as an extension to the standard Risks list in Project Server) we need to translate what the Project Manager / Team Members would like to state in words regarding probability & impact into a numeric value for sorting and analysis.

The following Choice columns are added to the Risk form.

User Interface Columns:

Column Type Values
Probability of Risk Choice Very Low, Low, Medium, High, Very High
Impact of Risk Choice Very Low, Low, Medium, High, Very High

Once we have the UI version of Probability and Impact, we need to use some hidden / calculated columns to convert these values in to numbers.

Once we have these values we then multiply them together:

Probability x Impact = Expected Outcome Value

Hidden Columns:

Column Type Values
Risk Probability Value Calculated Column =IF([Probability of Risk]=”Very Low”,0.1,IF([Probability of Risk]=”Low”,0.3,IF([Probability of Risk]=”Medium”,0.5,IF([Probability of Risk]=”High”,0.7,IF([Probability of Risk]=”Very High”,0.9,0)))))
Risk Impact Value Calculated Column =IF([Impact of Risk]=”Very Low”,0.05,IF([Impact of Risk]=”Low”,0.1,IF([Impact of Risk]=”Medium”,0.2,IF([Impact of Risk]=”High”,0.4,IF([Impact of Risk]=”Very High”,0.8,0)))))
Expected Value Result Calculated Column =[Risk Probability Value]*[Risk Impact Value]

Now that we have our Expected Outcome as a number, we can convert this back to a value the end user will understand, report and dashboard from.

RAG Outcome:

Column Type Values
RAG Calculated Column =IF([Expected Value Result]<0.05,”Green”,IF([Expected Value Result]>0.14,”Red”,”Amber”))

For each risk in the list we will now have a RAG value.

Further customisations I end up doing in clients include adding a RAG indicator column showing a graphical representation of the risk using jQuery.

RAG Indicator:

Column Type Values
RAG Indicator Calculated Column =”<div class=’convertToHTML’><img src=’/pwa/customisation/images/RAG” & [RAG] & “Sml.gif’ alt=”‘ & [RAG] & ‘” title=”‘ & [RAG] & ‘”></div>”

The above formula expects three images:

  • RAGGreenSml.gif
  • RAGAmberSml.gif
  • RAGRedSml.gif

Images in the formula are stored in a document library called:

  • Customisation

with a folder inside called:

  • images

Run the following jQuery function on the page with the list view on to convert the RAG Indicator calculated column string into rendered html:

1 function listViewCalcColChangeToHTML() { 2 $('table[class=ms-listviewtable]').find('td:contains("convertToHTML")').each(function() { 3 $(this).html($(this).text()); 4 }); 5 }

Using #jQuery to attach regular expression validation to a #SharePoint list form field #SP2010 #PS2010 #ProjectServer #in

January 19, 2011 4 comments

On one of my current projects I have had cause to ensure that no special characters are in the Title field of a SharePoint 2010 list form.

This is because we are using the Title field as the Plan Name in a Project Create process in Project Server 2010.  As a result we need to ensure that the Event Handler we are creating has validated data that the PS2010 PSI Web Service can accept for the Plan Name.

I created the following script to validate the data being entered into the Title field of the list form as it is being entered.

I manipulate the Save Buttons in the ribbon and the list form to ensure that the user cannot enter invalid data into the form.

To ensure a good user experience, I add an extra <DIV> element next to the Title field to notify the user of what is going on.

Example Code:

1 <script type='type/javascript'> 2 3 _spBodyOnLoadFunctionNames.push("attachToTitleField"); 4 5 function attachToTitleField() { 6 var titleField = $('input[title=Title]'); //Find title field on the form 7 8 //Add a DIV element to provide a place for an error message from the RegEx validation 9 titleField.parent().append("<div id='GilesH_titleValidation'></div>"); 10 11 //Use jQuery to attach the validateAlphanumeric function on keyup 12 titleField.keyup(function() { 13 validateAlphanumeric(titleField.val()); 14 }); 15 } 16 17 function validateAlphanumeric(stringValue) { 18 19 //Allows alphanumeric only for the 1st character 20 //after the 2nd character, alphanumeric and spaces allowed upto 255 characters 21 var regExpressionValue = /^[0-9A-Za-z][0-9A-Za-z\s]{0,255}$/; 22 var re = new RegExp(regExpressionValue); 23 24 if (stringValue.match(re)) { 25 //alert("Successful match"); //Debug 26 27 //Allow Save 28 $('a[id=Ribbon.ListForm.Edit.Commit.Publish-Large]').attr("style", "display:inline-block;"); //Show Ribbon Save Button 29 $('input[id*=SaveItem]').attr("disabled",""); //Re-enable Form Save Button 30 31 //Blank Error Message 32 $('div[id*=GilesH_titleValidation]').text(""); //Blank custom error message 33 } else { 34 //alert("No match"); //Debug 35 36 //Stop Save 37 $('a[id*=Ribbon.ListForm.Edit.Commit.Publish-Large]').attr("style", "display:none;"); //Hide Ribbon Save Button 38 $('input[id*=SaveItem]').attr("disabled","true"); //Disable Form Save Button 39 40 //Provide Error Message 41 $('div[id*=GilesH_titleValidation]').text("The title you have entered is invalid. Only alphanumeric characters and spaces are allowed."); 42 } 43 } 44 45 </script> 46 47